Java swing 窗体居中

时间:2023-01-28 00:26:52

1.顶层组件JFrame或者对话框JDialog居中

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height)
    frameSize.height = screenSize.height;       
if (frameSize.width > screenSize.width)
    frameSize.width = screenSize.width;       
frame.setLocation((screenSize.width-frameSize.width)/2,screenSize.height-frameSize.height) / 2);

2.显示器尺寸改变屏幕分辨率变化组件自适应

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setPreferredSize(new Dimension(512,450));           
int frameWidth = this.getPreferredSize().width;
int frameHeight = this.getPreferredSize().height;
frame.setSize(frameWidth, frameHeight);
frame.setLocation((screenSize.width - frameWidth) / 2,(screenSize.height - frameHeight) / 2);

3.Swing默认字体改变

Font vFont = new Font("Dialog", Font.PLAIN, 13);
UIManager.put("ToolTip.font", vFont);
UIManager.put("Table.font", vFont);
UIManager.put("TableHeader.font", vFont);
UIManager.put("TextField.font", vFont);
UIManager.put("ComboBox.font", vFont);
UIManager.put("TextField.font", vFont);
UIManager.put("PasswordField.font", vFont);
UIManager.put("TextArea.font", vFont);