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

标签 java swing actionlistener

当我单击相应的按钮时,我希望 GUI 在我在方法 paintComponent 中编码的确切位置上绘制圆形/矩形。

但我就是不知道如何继续下去。我应该告诉 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();
    }
}

最佳答案

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

  1. 切换适当的 boolean 值
  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);
}

关于java - ActionListener 在单独的面板上绘制形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39478827/

相关文章:

java - 表加载期间数据库的性能

java - 在java中使用emacs解析器?

java - JButton 和 actionPerformed 方法是否可能位于不同的文件中?

java - 在 Web 应用程序中绘制图形

java - 在 SpringBootApplication 类中使用服务会抛出 NullPointerException

java - 将面板添加到 BorderLayout 区域,元素未按应有的方式换行

java - 动态更新当前显示的工具提示

java - JTextField 缺失且布局错误地放置了 JButton

Java JButton addActionListener 并获取自己的名字

java - 将 JFileChooser 与 Swing GUI 类和监听器一起使用