使用 SSCCE 和变通方法编辑
我想以编程方式更改 JDialog 的位置。
public class SSCCE {
public static void main(String[] pArgs) {
JDialog dialog = new JDialog();
dialog.setSize(300, 300);
dialog.setLocation(10, 10);
dialog.setVisible(true);
}
}
但是,这不起作用,新对话框总是位于屏幕中央。我怀疑它与我的 L&F(Windows 7 64 位,jdk 1.6_30)有关,在将对话框设置为未修饰时,
public class SSCCEWorksButUndecorated {
public static void main(String[] pArgs) {
JDialog dialog = new JDialog();
dialog.setSize(300, 300);
dialog.setLocation(10, 10);
dialog.setUndecorated(true);
dialog.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
dialog.setVisible(true);
}
}
位置在我指定的高处。
但我需要一个经过修饰的对话框,之前有没有其他人遇到过这个问题,或者我是否遗漏了什么?
通过设置位置之后模式对话框的 setVisible() 解决方法
public class SSCCEWorkaroundForModalDialogs {
public static void main(String[] pArgs) {
final JDialog dialog = new JDialog();
dialog.setSize(300, 300);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
dialog.setLocation(10, 10);
}
});
dialog.setVisible(true);
}
}
最佳答案
移动方法文档说:
This method changes layout-related information, and therefore, invalidates the component hierarchy.
The method changes the geometry-related data. Therefore, the native windowing system may ignore such requests, or it may modify the requested data, so that the Window object is placed and sized in a way that corresponds closely to the desktop settings.
我假设您可以调用 revalidaite()
,然后再将对话框设置为可见。
关于java - JDialog setLocation 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11243086/