java - 虽然我已经设置了actionListener,但是按下按钮时没有任何反应

标签 java swing user-interface jbutton actionlistener

我正在学习 GUI,但遇到了问题。经过一晚上的思考,我彻底放弃了。如下面所示的代码,我希望在点击按钮后出现面板(TwoRectangle)。然而,当我按下它时,什么也没有发生。有人可以帮我解决这个问题吗?谢谢!.

class TwoRectangle extends JPanel implements ActionListener {
    Point p1;
    Point p2;
    int dx;
    int dy;

    public TwoRectangle() {
        p1 = new Point (20, 40);
        p2 = new Point (60, 10);
        dx = 5;
        dy = 5;

        Timer time = new Timer(100, this);
        time.start();

    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.fillRect(p1.x, p1.y, 70, 30);
        g.setColor(Color.BLUE);
        g.fillRect(p2.x, p2.y, 20, 80);

    }

    public void actionPerformed(ActionEvent e) {
        p1.x += dx;
        p2.y += dy;
        if (p1.x <= 0 || p1.x + 70 >= getWidth()) {
            dx = -dx;
        }
        if (p2.y <= 0 || p2.y + 80 >= getHeight()) {
            dy = -dy;
        }
        repaint();
    }
}

public class ObjectsAppear {
    public static void main (String args[]) {

        ObjectsAppear appear = new ObjectsAppear();
    }

    JFrame frame;
    JButton button;
    JLabel label;

    public ObjectsAppear() {

        label = new JLabel("Hit play to execute");
        button = new JButton("Play");
        JPanel north = new JPanel(new FlowLayout());
        north.add(label);
        north.add(button);


        frame = new JFrame("Window Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setSize(new Dimension(300,400));
        frame.add(north, BorderLayout.NORTH);

        // This is the code to make the panel to appear 
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                TwoRectangle display = new TwoRectangle();
                display.setBackground(Color.WHITE);
                frame.add(display, BorderLayout.CENTER);
            }
        });

        frame.setVisible(true);

    }
}

最佳答案

动态添加组件到容器时,如果容器已经可见,则需要重新验证容器。

只需添加

frame.revalidate();

actionPerformed() 方法的末尾。

关于java - 虽然我已经设置了actionListener,但是按下按钮时没有任何反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32164095/

相关文章:

Java返回组件

java - 如何设置滚动 Pane 内文本区域的背景颜色?

java - JFrame 不保持显示 - java

java - 有什么方法可以使 JCombobox 中的文本右对齐

java - 条件挑战

java - 如何在浏览器中显示来自byte[]流的pdf?

用于显示网页并返回 HTML 的 Java GUI

java - 我的循环是错误的。全新的 Java。关于我哪里出错的任何见解?我应该计算硬币

java - 如何根据应用程序运行的系统加载不同的 native 库(dll、so)

java - 使用键对象化投影查询