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

时间:2016-09-13 20:54:41

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

2 个答案:

答案 0 :(得分:2)

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

  1. 切换适当的布尔值
  2. 在执行绘画的repaint实例上调用JPanel
  3. 完成这些步骤的一种方法是使用单个切换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);
    }
    

答案 1 :(得分:1)

我不知道您使用全局boolean变量b的内容但是我注意到您在按repaint()时必须调用Button方法。< / p>

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

}