2012-07-26 82 views
2

我编写我的Swing应用程序时总是遇到这个问题,我想我终于会得到一个明确的答案,而不是玩弄它直到我得到它的工作...如何从JButton的ActionListener中从JFrame中删除JButton?

我有一个JFrame。在这个JFrame内部是一个JButton。在ActionListener中,我想几乎清空JFrame,留下一个或两个组件(这将包括删除JButton)。应用程序然后冻结,因为在ActionListener完成之前您无法删除该组件。我该如何解决这个问题?

回答

7

当您拆卸组件时,请不要忘记在容器上调用validate()repaint(),并且应该可以正常工作。

import java.awt.Component; 
import java.awt.Container; 
import java.awt.FlowLayout; 
import java.awt.event.ActionEvent; 
import javax.swing.AbstractAction; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 

public class RemoveDemo { 

    static class RemoveAction extends AbstractAction{ 
     private Container container; 

     public RemoveAction(Container container){ 
      super("Remove me"); 
      this.container = container; 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      container.remove((Component) e.getSource()); 
      container.validate(); 
      container.repaint();  
     } 
    } 

    private static void createAndShowGUI() { 
     final JFrame frame = new JFrame("Demo"); 
     frame.setLayout(new FlowLayout()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     RemoveAction action = new RemoveAction(frame); 
     frame.add(new JButton(action)); 
     frame.add(new JButton(action)); 

     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       createAndShowGUI(); 
      } 
     }); 
    } 
} 
+0

+1 [sscce](http://sscce.org/)。还要考虑“行动”。 – trashgod 2012-07-26 03:57:35

+0

@trashgod谢谢,更新了Action。 – tenorsax 2012-07-26 04:13:10

+0

示例性的。您的工作代码只需要最初的'invokeLater()',这也引发了一个问题,即为什么CPCookieMan(看不见的)代码冻结。 – trashgod 2012-07-26 04:26:51

3

使用EventQueue.invokeLater()在事件队列中添加合适的Runnable。它会在处理完所有待处理事件后发生。“

+0

是的,很好的+1 – tenorsax 2012-07-26 03:52:03

+1

也是我的+1,尽管Max的例子让我更容易找到问题。谢谢,无论哪种方式。 – Paulywog 2012-07-26 04:48:32