2012-07-26 76 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