junxi junxi - 2 months ago 20
Java Question

Writing an ActionListener to draw shapes by pressing button

I need to write a GUI that draws circles/lines every time I press the button Draw Circle/Draw Line.

The frame works just fine but I have trouble implementing the ActionListener for this program. I don't know how to connect the buttons with "boolean circZ". Everything I tried gives me errors.

Maybe you can help.

public class fram extends JFrame {
fram(){
JPanel panel = new JPanel();
add(panel);
JButton btn1 = new JButton("Draw Circle");
JButton btn2 = new JButton("Draw Lines");
panel.add(btn1);
panel.add(btn2);
MyPanel obj = new MyPanel();
panel.add(obj);
}

public class MyPanel extends JPanel{
public boolean circZ = true;

public void paintComponent(Graphics g){**
super.paintComponent(g);
if(cicZ == true){
g.setColor(Color.BLACK);
g.drawOval(150, 50, 50, 50);
}else if(circZ==false){
...
}
}
}

public class CRListener implements ActionListener(){

!!! I DO NEED HELP HERE !!!
}

public static void main(String[]args){
fram f = new fram();
f.paint(null);
}

Answer

You can accomplish what you are trying to do by adding anonymous ActionListeners to your buttons (see below). You need to either make your MyPanel final, or a member in the containing fram so that it can be referenced later.

NOTE: In this design, it would be cleaner to make MyPanel an inner class of fram and circZ a member of fram

   MyPanel obj;
   fram(){
      JPanel panel = new JPanel();
      add(panel);
      JButton btn1 = new JButton("Draw Circle");
      JButton btn2 = new JButton("Draw Lines");
      btn1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
           obj.circZ =...;
        }
      });
      btn2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
           obj.circZ =...;
        }
      });
      panel.add(btn1);
      panel.add(btn2);
      obj = new MyPanel();
      panel.add(obj);
  }