当前位置: 代码迷 >> java >> 单击按钮时无法重新绘制圆圈
  详细解决方案

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

热度:53   发布时间:2023-07-31 11:14:47.0

单击按钮时,我无法使窗口重绘。 当我单击按钮时,应该发生的情况是应该在框架上绘制更多的圆(从技术上讲,应该是上次绘制的圆数* 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
    }
}

我不知道事件或重绘的概念是否正确,因此任何帮助/指针都将不胜感激。 谢谢!

您不想第二次创建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);
    }

问题是您要创建两个Roach实例。 一个添加为JButton的动作侦听器,另一个添加到要绘制的框架。 由于它们是不同的实例,因此绘制的蟑螂永远不会收到动作,因此总计数为1。

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

  相关解决方案