我有一個可浮動的工具欄,用戶可以在他方便的時候移動,我想保留最後一個位置,以便在下次啓動時在同一位置找到它。當它改變時獲取可浮動的JToolBar位置
我使用的是BorderLayout
,因此工具欄可以停靠在北,南,東或西(或在一個單獨的框架中),因此我可以撥打BorderLayout.getConstraints()
來獲取其BorderLayout約束。
我註冊了AncestorListener
來趕上ancestorMoved()
回調,但它被隨機調用。 A ComponentListener
具有相同的效果(componentMoved()
回調)。
如果我定期查詢工具欄上的限制,雖然我可以看到它的變化,所以我可以查詢它時,我的應用程序退出,但我想知道爲什麼我的聽衆不會被調用,因爲我希望它會是。
在我的Ubuntu Oracle JDK 1.7_80上運行以下SSCCE,我將工具欄從北到西 - >無輸出。西南 - >工作。從東南方向 - >作品。東到北 - >工作。從北到西 - >沒有輸出,... 在Oracle JDK 1.8.0_102和Windows上也有相同的行爲。
class ToolBarPos extends JFrame {
private static final long serialVersionUID = 1L;
ToolBarPos() {
super();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
Container cp = getContentPane();
final BorderLayout layout = new BorderLayout();
cp.setLayout(layout);
final JToolBar tb = new JToolBar();
cp.add(tb, BorderLayout.NORTH);
tb.addAncestorListener(new AncestorListener() {
@Override public void ancestorAdded(AncestorEvent event) { }
@Override public void ancestorRemoved(AncestorEvent event) { }
@Override public void ancestorMoved(AncestorEvent event) {
String pos = (String)layout.getConstraints(event.getComponent()); // null if detached
System.out.println("Moved "+pos+".");
}
});
tb.add(new JLabel("Element"));
cp.add(new JLabel("CENTER"), BorderLayout.CENTER);
}
public static void main(String[] args) {
new ToolBarPos().setVisible(true);
}
}