gpt4 book ai didi

java - 检测用户何时关闭 float 工具栏框架

转载 作者:行者123 更新时间:2023-11-29 05:44:48 27 4
gpt4 key购买 nike

当用户试图在 swing 中关闭 float 工具栏窗口时是否可以捕获事件?提前致谢。

最佳答案

可能有一些非常简单的解决方案,但您为什么要使用它?

我能想出的最好办法(没有扩展我自己的工具栏)是向工具栏添加一个 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());
}

}

关于java - 检测用户何时关闭 float 工具栏框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16211228/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com