点击按钮时无法重新绘制圆圈

时间:2011-03-29 01:07:26

标签: java events swing awt

单击按钮时,我无法对窗口进行重新绘制。单击按钮时应该发生的事情是在框架上绘制更多圆圈(技术上应该是上次绘制的圆圈数量* 2)。由于某种原因,它不起作用,我无法弄清楚为什么它不会重新绘制。这是我的代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Roaches {  
    public static void main(String[] args) {
        //Create the frame
        JFrame frame = new JFrame();
        //Set the frame's size
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Roaches!");
        //Create the button
        JButton button = new JButton("Multiply Roaches!");
        button.addActionListener(new Roach());
        JPanel buttonPanel = new JPanel();
        //Add the button to the panel
        buttonPanel.add(button);
        //Add the panel to the frame
        frame.add(buttonPanel, BorderLayout.SOUTH);
        //Add the roach panel to the frame
        frame.add(new Roach());
        //Make frame visible
        frame.setVisible(true);
    }
}
class Roach extends JComponent implements ActionListener {
    //Keep track of how many roaches to draw
    private int roachCount = 1;
    protected void paintComponent(Graphics g) {
        Graphics2D gr = (Graphics2D)g;
        for(int i = 0; i < roachCount; i++) {
            int x = 5 * i;
            int y = 5 * 1;
            gr.drawOval(x, y, 50, 50);
        }
        System.out.println("REPAINT"); //For testing
    }
    public void actionPerformed(ActionEvent e) {
        roachCount = roachCount * 2;
        repaint();
        System.out.println("CLICK!!!!"); //For testing
    }
}

我不知道我是否有事件的概念或重新绘制错误,所以任何帮助/指针都将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:3)

您不希望第二次创建new Roach()。只需创建一个蟑螂并保留对它的引用,并在任何地方使用引用。

 public static void main(String[] args) {
        //Create the frame
        JFrame frame = new JFrame();
        //Set the frame's size
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Roaches!");
        //Create the button
        JButton button = new JButton("Multiply Roaches!");

        Roach roach = new Roach();

        button.addActionListener(roach);
        JPanel buttonPanel = new JPanel();
        //Add the button to the panel
        buttonPanel.add(button);
        //Add the panel to the frame
        frame.add(buttonPanel, BorderLayout.SOUTH);
        //Add the roach panel to the frame
        frame.add(roach);
        //Make frame visible
        frame.setVisible(true);
    }

答案 1 :(得分:3)

问题在于您正在创建两个Roach实例。您添加为JButton的动作侦听器,另一个添加到要绘制的帧的动画侦听器。因为它们是不同的实例,所绘制的Roach永远不会收到动作,因此始终具有1的计数。

这实际上是一个很好的例子,说明为什么我不喜欢在gui对象上实现监听器接口的做法。