最初,我在桌面Swing应用程序中使用了以下代码。MyDialog是内部类,frame是JFrame。
private class MyDialog extends JDialog {
public MyDialog (String title) {
super(frame, title, true);
...
}然后,我修改了这段代码,以支持桌面和applet。所以就变成这样了。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 for mKorbel:
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();
}
}发布于 2013-01-15 11:23:58
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);
}https://stackoverflow.com/questions/14332196
复制相似问题