gpt4 book ai didi

java - 如何从 JFrame 中删除 JButton?

转载 作者:行者123 更新时间:2023-12-02 04:42:33 39 4
gpt4 key购买 nike

我想在用户单击 JButton 时删除 JButton

我知道我应该使用删除方法,但它不起作用。

我该怎么做?

这是我的代码:

class Game implements ActionListener {

JFrame gameFrame;
JButton tmpButton;
JLabel tmpLabel1, tmpLabel2, tmpLabel3, tmpLabel4;

public void actionPerformed(ActionEvent e) {
gameFrame.remove(tmpLabel1);
gameFrame.getContentPane().validate();
return;
}

Game(String title) {
gameFrame = new JFrame(title);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setBounds(100, 100, 300, 500);
gameFrame.setResizable(false);
gameFrame.getContentPane().setLayout(null);

tmpLabel4 = new JLabel(new ImageIcon("./images/bomber.jpg"));
tmpLabel4.setSize(200, 200);
tmpLabel4.setLocation(50, 100);
tmpButton = new JButton("Play");
tmpButton.setSize(100, 50);
tmpButton.setLocation(100, 350);
tmpButton.addActionListener(this);

gameFrame.getContentPane().add(tmpLabel4);
gameFrame.getContentPane().add(tmpButton);
gameFrame.setVisible(true);
}
}

最佳答案

如果隐藏按钮而不是删除代码的工作,那么您可以使用:

public void actionPerformed(ActionEvent event){
tmpButton.setVisible(false);
}

对于按钮。但按钮只是隐藏而不是删除。

关于java - 如何从 JFrame 中删除 JButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27587048/

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