junxi junxi - 1 year ago 63
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

when I click on the respective buttons.

But I just don't know how to go on. What should I tell
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();

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));

MyPanel obj = new MyPanel();


setSize(400, 250);

public class MyPanel extends JPanel {

public boolean circleZ = true;

public void paintComponent(Graphics g) {
if (circleZ = true) {
g.drawOval(150, 50, 50, 50);
} else if (circleZ = false) {
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 Source

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;
    public void actionPerformed(ActionEvent e) {
         panel.circleZ = !panel.circleZ;

And when you paint:

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