怎么区分 是点击了非模态的JDialog还是父窗口
时间: 2024-04-09 15:32:39 浏览: 60
要区分是点击了非模态的JDialog还是父窗口,可以使用WindowFocusListener监听器结合Component的isShowing方法来实现。
首先,对JDialog和父窗口都添加WindowFocusListener监听器,并在windowGainedFocus方法中进行判断。如果是JDialog获取焦点,则通过调用isShowing方法来判断该JDialog是否可见,如果可见则是点击了非模态的JDialog,否则是点击了父窗口。
下面是修改后的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
public class NonModalDialogExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Parent Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
JButton openDialogButton = new JButton("Open Dialog");
openDialogButton.addActionListener(e -> {
JDialog dialog = new JDialog(frame, "Non-Modal Dialog", false);
dialog.addWindowFocusListener(new FocusListener());
dialog.setSize(200, 100);
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
});
frame.getContentPane().add(openDialogButton);
frame.addWindowFocusListener(new FocusListener());
frame.setVisible(true);
}
static class FocusListener implements WindowFocusListener {
@Override
public void windowGainedFocus(WindowEvent e) {
if (e.getSource() instanceof JDialog) {
JDialog dialog = (JDialog) e.getSource();
if (dialog.isShowing()) {
System.out.println("Clicked Non-Modal JDialog");
}
} else if (e.getSource() instanceof JFrame) {
JFrame frame = (JFrame) e.getSource();
System.out.println("Clicked Parent Window");
}
}
@Override
public void windowLostFocus(WindowEvent e) {
// Do nothing
}
}
}
```
在上述示例中,当焦点从JDialog移出或从父窗口移出时,会判断焦点获取的源对象,如果是JDialog并且JDialog是可见的,则是点击了非模态的JDialog;如果焦点获取的源对象是父窗口(JFrame),则是点击了父窗口。
希望能帮到你!如果还有其他问题,请继续提问。
阅读全文