我写了一个JWindow,类似于我的应用程序中的精美菜单,当用户按下按钮时弹出。然而,如果用户在主窗口中的任何地方单击,我希望它消失。当然,我可以向主窗口添加鼠标监听器,但这并不会将其添加到窗口本身上的所有组件中,而且循环遍历所有组件似乎有点蛮力的解决方案(如果窗口上的组件发生更改,则无法保证其有效)。
如何最好地处理这样的事情?
如何最好地处理这样的事情?
Toolkit.getDefaultToolkit().addAWTEventListener(listener, eventMask)
。找到过滤仅限鼠标点击的eventMask。这个AWT监听器是整个应用程序的全局监听器,因此您可以看到发生的所有事件。import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogDeactivated
{
public static void main(String[] args)
{
final WindowListener wl = new WindowAdapter()
{
public void windowDeactivated(WindowEvent e)
{
e.getWindow().setVisible(false);
}
};
JButton button = new JButton("Show Popup");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
JFrame frame = (JFrame) SwingUtilities.windowForComponent(button);
JDialog dialog = new JDialog(frame, false);
dialog.setUndecorated(true);
dialog.add( new JButton("Dummy Button") );
dialog.pack();
dialog.setLocationRelativeTo( frame );
dialog.setVisible( true );
dialog.addWindowListener( wl );
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(button, BorderLayout.NORTH);
frame.setSize(400, 400);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
windowDeactiveated()
事件似乎从来没有得到注册,这有点奇怪。在使用 JFrame
时它很好用,但是一旦我切换到 JWindow
上,就不能正常工作了。不知道您是否有任何想法可以解决这个问题?我现在已经用另一种方法实现了,但是我很感兴趣 :) - Michael Berry