2013-04-25 62 views

回答

3

可能有一些非常簡單的解決方案,但爲什麼要使用它?

我能想出的最好(沒有伸出自己的工具欄)是一個AncestorListener添加到工具欄和監督它的事件。

我有這種方法的問題,不過,是你需要知道你最初連接到主框架,這可能不是很方便。

import java.awt.BorderLayout; 
import java.awt.EventQueue; 
import java.awt.event.ComponentEvent; 
import java.awt.event.ComponentListener; 
import java.awt.event.ContainerEvent; 
import java.awt.event.ContainerListener; 
import java.awt.event.HierarchyEvent; 
import java.awt.event.HierarchyListener; 
import java.beans.PropertyChangeEvent; 
import java.beans.PropertyChangeListener; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JToolBar; 
import javax.swing.SwingUtilities; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 
import javax.swing.event.AncestorEvent; 
import javax.swing.event.AncestorListener; 

public class TestFloatingToolBar { 

    public static void main(String[] args) { 
     new TestFloatingToolBar(); 
    } 

    public TestFloatingToolBar() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       final JFrame frame = new JFrame("Test"); 

       final JToolBar tb = new JToolBar(); 
       tb.add(new JButton("Pop")); 
       tb.setFloatable(true); 

       tb.addAncestorListener(new AncestorListener() { 
        @Override 
        public void ancestorAdded(AncestorEvent event) { 
         tell(); 
         if (SwingUtilities.getWindowAncestor(tb).equals(frame)) { 
          System.out.println("...In Main Frame"); 
         } else { 
          System.out.println("...Maybe floating"); 
         } 
        } 

        @Override 
        public void ancestorRemoved(AncestorEvent event) { 
         tell(); 
         if (SwingUtilities.getWindowAncestor(tb).equals(frame)) { 
          System.out.println("...In Main Frame"); 
         } else { 
          System.out.println("...Maybe floating"); 
         } 
        } 

        @Override 
        public void ancestorMoved(AncestorEvent event) { 
        } 
       }); 

       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(tb, BorderLayout.NORTH); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 

     }); 
    } 

    public void tell() { 
     Exception exp = new Exception(); 
     StackTraceElement[] stackTrace = exp.getStackTrace(); 
     System.out.println(stackTrace[1].getMethodName()); 
    } 

} 
+1

+1或Component/HierarchyListener [例如](http://stackoverflow.com/q/10880326/714968) – mKorbel 2013-04-25 09:56:43