ActionListener 在单独的面板上绘制形状

ActionListener to draw shapes on separate panel

我希望我的 GUI 在我单击相应按钮时在方法 paintComponent 中编码的确切位置绘制 circles/rectangles。

但我只是不知道如何继续下去。我应该告诉 actionPerformed 做什么?尝试了几个小时想出一个办法,但我只收到错误。

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

我不知道你在使用全局 boolean 变量 b 是为了什么 但我注意到当你按下 Button 时你必须调用 repaint() 方法.

public class KRListener implements ActionListener {

    boolean b;

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

    @Override
    public void actionPerformed(ActionEvent e){
        //add some code here to change properties of the drawing before calling the repaint method?

        repaint();
    }

}

假设我清楚地理解了问题(您希望在矩形或圆形之间切换),在 ActionListener 实现中您需要:

  1. 切换适当的布尔值
  2. 在执行绘画的 JPanel 实例上调用 repaint

完成这些步骤的一种方法是使用一个开关 JButton,并将用于绘图的 JPanel 的实例传递给您的 ActionListener 实现,它可以被使用完成以上两个步骤:

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

当你画画时:

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