junxi junxi - 2 months ago 12
Java Question

ActionListener to draw shapes on separate panel

I want my GUI to draw circles/rectangles on the exact position I coded in the method

paintComponent
when I click on the respective buttons.

But I just don't know how to go on. What should I tell
actionPerformed
to do? Trying for a few hours to figure out a way, but I'm only getting errors.

public class Kreise extends JFrame {

Kreise() {
setLayout(new GridLayout(2, 1));
JLabel label = new JLabel("Draw Circ / Rect here: ");
label.setLayout(new FlowLayout(FlowLayout.CENTER));

JPanel jp1 = new JPanel();
jp1.setBackground(Color.LIGHT_GRAY);;
jp1.add(label);

JPanel jp2 = new JPanel(new FlowLayout());
JButton circ = new JButton("Circle");
JButton rect = new JButton("Rectangle");

circ.addActionListener(new KRListener(true));
rect.addActionListener(new KRListener(false));
jp2.add(circ);
jp2.add(rect);

MyPanel obj = new MyPanel();
jp1.add(obj);

add(jp1);
add(jp2);

setSize(400, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}

public class MyPanel extends JPanel {

public boolean circleZ = true;

public void paintComponent(Graphics g) {
if (circleZ = true) {
super.paintComponent(g);
g.drawOval(150, 50, 50, 50);
} else if (circleZ = false) {
super.paintComponent(g);
g.drawRect(150, 50, 50, 50);
}
}
}

public class KRListener implements ActionListener {

boolean b;

KRListener(boolean b) {
this.b = b;
}

public void actionPerformed(ActionEvent e) {
?
}

}

public static void main(String[] args) {
new Kreise();
}
}

Answer

Presuming I understand the question clearly (you wish to toggle between the a rectangle or circle), in the ActionListener implementation you need to:

  1. Toggle the appropriate boolean value
  2. Call repaint on the JPanel instance that performs the painting

One way to accomplish these steps is to have a single toggle JButton, and pass an instance of the JPanel used for drawing to your ActionListener implementation, which can be used to accomplish both steps above:

public class KRListener implements ActionListener {

    private MyPanel panel;

    KRListener(MyPanel panel) {
        this.panel = panel;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
         panel.circleZ = !panel.circleZ;
         panel.repaint();
    }
}

And when you paint:

if ( circleZ ){
    g.drawOval(150, 50, 50, 50);
}else{
    g.drawRect(150, 50, 50, 50);
}
Comments