gpt4 book ai didi

java - 虽然我已经设置了 actionListener,但按下按钮时什么也没有发生

转载 作者:行者123 更新时间:2023-11-30 08:47:59 26 4
gpt4 key购买 nike

我正在学习 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com