I am kinda new to java and would like to invoke a graphical method in ActionEvent, for instance let's say I would like a square to be drawn when button b is pressed? Will appreciate any help thanks:
package Mst;
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class Cours2_2 extends Applet implements ActionListener {
Button a,b,c;
public void init(){
setBackground(Color.pink);
a= new Button("KIRMIZI");
a.addActionListener(this);
add(a);
b= new Button("BEYAZ");
b.addActionListener(this);
add(b);
c= new Button("SARI");
c.addActionListener(this);
add(c);
}
public void paint(Graphics g){
g.drawString("s", 5, 5);
}
public void actionPerformed(ActionEvent e){
String s= e.getActionCommand();
if(s.equals("KIRMIZI")){
setBackground(Color.red);
}
if(s.equals("BEYAZ")){
setBackground(Color.white);
}
if(s.equals("SARI")){
setBackground(Color.yellow);
}
drawStrings(t);
}
public void drawStrings(Graphics t) {
t.setColor(Color.yellow);
t.fillRect(0, 0, 75 ,75);
}
}
I would like to know if I should create this square which I want drawn when a button is pressed as a method or a function. Thanks
Applet, if you "really" have to, useJAppletinstead. Having said that, you should start withJPaneland override it'spaintComponentmethod instead (and make sure you callsuper.paintComponentbefore doing any custom painting. Take a look at Painting in AWT and Swing and Performing Custom Painting for more details.paintmethods should paint the current state of the component. This means that you will need to provide some information and logic that the paint methods can use to make decisions about what to paint. For example, you could have a flag, which is changed by theActionListener, which callsrepainton your component and when the component is painted, you would test the state of this flag and make decisions on what should be done (like drawing a square for example).A more complicated approach might use a
Listand take advantage of theShapeAPI, adding or removing shapes to theListwhich the paint method would then be able to iterate over and paintHave a look at Collections Trail and 2D Graphics for more details