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, useJApplet
instead. Having said that, you should start withJPanel
and override it'spaintComponent
method instead (and make sure you callsuper.paintComponent
before doing any custom painting. Take a look at Painting in AWT and Swing and Performing Custom Painting for more details.paint
methods 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 callsrepaint
on 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
List
and take advantage of theShape
API, adding or removing shapes to theList
which the paint method would then be able to iterate over and paintHave a look at Collections Trail and 2D Graphics for more details