最初我在桌面 Swing 应用程序中使用了以下代码。 MyDialog 是内部类,frame
是 JFrame。
private class MyDialog extends JDialog {
public MyDialog (String title) {
super(frame, title, true);
...
}
然后我修改了这段代码以支持桌面和小程序。所以就变成了这个样子。 owber
是 JFrame
或 JApplet
。
private class MyDialog extends JDialog {
public MyDialog (String title) {
super(SwingUtilities.windowForComponent(owner), title, ModalityType.APPLICATION_MODAL);
...
}
问题是我将代码作为桌面运行,但模态行为不同。应用程序启动后,我在任务栏中单击 Eclipse,因此应用程序隐藏在 Eclipse 后面。现在在任务栏中,我单击应用程序图标:
JFrame
和JDialog
立即显示在 Eclipse 之上- 在任务栏中有两个选项
JFrame
和JDialog
,但是对于这两个选项,只有 JDialog 出现在 Eclipse 之上,而 JFrame 则没有。
而且 JDialod 没有以下最适合我的构造函数:
JDialog(Window owner, String title, boolean modal)
我尝试了 ModalityType
中的不同字段,但没有一个能给出与片段 #1 相同的期望结果。我的方法有什么问题以及为什么行为不同?
UPD:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WindowForComp {
private JFrame mainwindow;
private CustomDialog customDialog;
private void displayGUI() {
mainwindow = new JFrame("MyFrame");
customDialog = new CustomDialog(mainwindow, "Modal Dialog", true);
mainwindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
JButton mainButton = new JButton("Just a button");
mainButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
customDialog.setVisible(true);
}
});
}
});
contentPane.add(mainButton);
mainwindow.setContentPane(contentPane);
mainwindow.pack();
mainwindow.setLocationByPlatform(true);
mainwindow.setVisible(true);
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new WindowForComp().displayGUI();
}
});
}
}
class CustomDialog extends JDialog {
public CustomDialog(JFrame owner, String title, boolean modal) {
super(SwingUtilities.windowForComponent(owner), title, ModalityType.APPLICATION_MODAL);
System.out.println(SwingUtilities.windowForComponent(owner));
JPanel contentPane = new JPanel();
JLabel dialogLabel = new JLabel("I am a Label on JDialog.", JLabel.CENTER);
contentPane.add(dialogLabel);
setContentPane(contentPane);
pack();
}
}
最佳答案
似乎 SwingUtilities.windowForComponent(JFrame)
返回 null,因此对话框没有父级。
SwingUtilities.windowForComponent(JFrame) returns null
现在我改用这个方法,它工作得很好(模态):
public static Window windowForComponent (Component c) {
if (c instanceof Window) return (Window)c;
return SwingUtilities.windowForComponent(c);
}
关于java - JDialog modal=true 与 ModalityType.APPLICATION_MODAL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14332196/