我正在尝试在第二个屏幕上打开一个JFrame并将其居中。我可以在第二个屏幕上打开JFrame,但如何将其居中呢?以下是我编写的示例代码:
import javax.swing.*;
import java.awt.*;
public class Question {
public Question() {
JFrame f = new JFrame();
JPanel panel = new JPanel();
f.getContentPane().add(panel);
f.pack();
f.setTitle("Hello");
f.setSize(200,200);
showOnScreen(1,f);
f.setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
new Question();
}
};
SwingUtilities.invokeLater(r);
}
public static void showOnScreen( int screen, JFrame frame ) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
if( screen > -1 && screen < gd.length ) {
frame.setLocation(gd[screen].getDefaultConfiguration().getBounds().x, frame.getY());
} else if( gd.length > 0 ) {
frame.setLocation(gd[0].getDefaultConfiguration().getBounds().x, frame.getY());
} else {
throw new RuntimeException( "No Screens Found" );
}
}
}
我尝试了以下类似的方法来在第二个屏幕上居中显示它:
frame.setLocation((gd[screen].getDefaultConfiguration().getBounds().x*3/2)-200, ((gd[screen].getDefaultConfiguration().getBounds().height)/2)-200);
它可以工作,但我不想硬编码大小,因为在实际程序中,框架大小可能会改变。
另外,我尝试了这个:
frame.setLocation((gd[screen].getDefaultConfiguration().getBounds().width)/2-frame.getSize().width/2, (gd[screen].getDefaultConfiguration().getBounds().height)/2-frame.getSize().height/2);
但是它会在第一个屏幕上打开。这很合理。 请有人帮忙应用正确的修复方法。感谢您的帮助。谢谢。
f.setVisible()
之前或之后放置f.setLocationRelativeTo(null);
。 - Madhan