[英]How can I remove JButton from JFrame?
I want to remove JButton
when user click JButton
. 我想删除JButton
当用户点击JButton
。
I know that I should use remove method, but it did not work. 我知道我应该使用remove方法,但它不起作用。
How can I do this? 我怎样才能做到这一点?
Here is my code: 这是我的代码:
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);
}
}
If hiding the button instead of removing works for your code then you can use: 如果隐藏按钮而不是删除代码的工作,那么您可以使用:
public void actionPerformed(ActionEvent event){
tmpButton.setVisible(false);
}
for the button.But the button is just hidden not removed. 按钮。然后隐藏按钮不被删除。
The simplest solution might be to... 最简单的解决方案可能是......
ActionListener
to the button, see How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details 将ActionListener
附加到按钮,请参阅如何使用按钮,复选框和单选按钮以及如何编写动作侦听器以获取更多详细信息 ActionListener
is clicked, extract the source of the event, JButton buttonThatWasClicked = (JButton)actionEvent.getSource()
单击ActionListener
,提取事件的源, JButton buttonThatWasClicked = (JButton)actionEvent.getSource()
For example... 例如...
Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revaidate();
parent.repaint();
As some ideas... 作为一些想法......
First of all in your actionPerformed method you need to check that the button is clicked or not. 首先,在actionPerformed方法中,您需要检查是否单击了按钮。 And if the button is clicked, remove it. 如果单击该按钮,请将其删除。 Here's how : 这是如何做 :
if(e.getSource() == tmpButton){
gameFrame.getContentPane().remove(tmpButton);
}
add this to your actionPerformed Method 将其添加到actionPerformed方法中
don't add your button to jframe but add each component you want! 不要将您的按钮添加到jframe,而是添加您想要的每个组件!
public void actionPerformed(ActionEvent event)
{
//gameFrame.getContentPane().add(tmpButton); -=> "Commented Area"
gameFrame.getContentPane().validate();
}
or hide your button like this 或隐藏你的按钮
public void actionPerformed(ActionEvent event)
{
tmpButton.setVisible(false);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.