java 如何从 JFrame 中删除 JButton?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27587048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:03:46  来源:igfitidea点击:

How can I remove JButton from JFrame?

javaswingjbutton

提问by Won Seok Lee

I want to remove JButtonwhen 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);
}
}

回答by hermit

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.

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

回答by MadProgrammer

The simplest solution might be to...

最简单的解决方案可能是...

For example...

例如...

Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revaidate();
parent.repaint();

As some ideas...

作为一些想法...

回答by varun

First of all in your actionPerformed method you need to check that the button is clicked or not. And if the button is clicked, remove it. Here's how :

首先,在您的 actionPerformed 方法中,您需要检查按钮是否被点击。如果单击该按钮,请将其删除。就是这样 :

if(e.getSource() == tmpButton){
   gameFrame.getContentPane().remove(tmpButton);
}

add this to your actionPerformed Method

将此添加到您的 actionPerformed 方法中

回答by Mohammadreza Khatami

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);
}