繁体   English   中英

如何从JFrame中删除JButton?

[英]How can I remove JButton from JFrame?

我想删除JButton当用户点击JButton

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

我怎样才能做到这一点?

这是我的代码:

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

按钮。然后隐藏按钮不被删除。

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

例如...

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

作为一些想法......

首先,在actionPerformed方法中,您需要检查是否单击了按钮。 如果单击该按钮,请将其删除。 这是如何做 :

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

将其添加到actionPerformed方法中

不要将您的按钮添加到jframe,而是添加您想要的每个组件!

public void actionPerformed(ActionEvent event)
{
   //gameFrame.getContentPane().add(tmpButton); -=> "Commented Area"
   gameFrame.getContentPane().validate();
}

或隐藏你的按钮

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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