how to call a graphical method in actionperformed?

936 views Asked by At

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

1

There are 1 answers

3
MadProgrammer On
  1. Avoid Applet, if you "really" have to, use JApplet instead. Having said that, you should start with JPanel and override it's paintComponent method instead (and make sure you call super.paintComponent before doing any custom painting. Take a look at Painting in AWT and Swing and Performing Custom Painting for more details.
  2. Generally speaking, painting in AWT/Swing is passive, that is, when the system "decides" something needs to be updated, it will then be painted. This means that you (generally) have little control over when something will be painted. You make suggestions, but it's update to the system to decide what and when something is painted.
  3. You 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 the ActionListener, which calls repaint 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 the Shape API, adding or removing shapes to the List which the paint method would then be able to iterate over and paint

Have a look at Collections Trail and 2D Graphics for more details