通常我使用 setLocationRelativeTo(null)
在屏幕中心显示我的对话框,但最近我买了第二个显示器,这种方法总是把我的对话框放在主监视器的中心位置,即使主窗口在第二个监视器上。
我知道这是一件小事,但它让我很烦恼,有没有其他解决方案?我从来没试过相对于主屏幕设置位置。
通常我使用 setLocationRelativeTo(null)
在屏幕中心显示我的对话框,但最近我买了第二个显示器,这种方法总是把我的对话框放在主监视器的中心位置,即使主窗口在第二个监视器上。
我知道这是一件小事,但它让我很烦恼,有没有其他解决方案?我从来没试过相对于主屏幕设置位置。
我知道这个问题很老了...但对于像我一样的疯狂程序员:
创建自己的类,扩展JDialog并使用super(Frame,Modal)。
这对我起作用了:
import java.io.File;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class GFileChooserDialog extends JDialog {
private JFileChooser fileChooser;
private File file;
public GFileChooserDialog(JFrame relativeTo) {
super(relativeTo, true);
this.setAlwaysOnTop(true);
this.fileChooser = new JFileChooser();
this.getContentPane().setSize(450, 300);
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = fileChooser.getSelectedFile();
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
通过使用 单例模式 用于主框架,您可以像这样调用对话框:
new GFileChooserDialog(Singelton.getInstance());
@Override
public void paint(Graphics g) {
super.paint(g);
Rectangle screen = this.getGraphicsConfiguration().getBounds();
this.setLocation(
screen.x + (screen.width - this.getWidth()) / 2,
screen.y + (screen.height - this.getHeight()) / 2
);
}