简体   繁体   English

如何从JFrame中删除JButton?

[英]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... 最简单的解决方案可能是......

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM