作者在 2011-11-27 19:09:50 发布以下内容
对于让JFame窗口居中,我们可以自己写方法来处理,为了方便,我把代码封装在了一个方法里:
public void moveToCenter(JFrame frame) {
//先获得屏幕大小
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();//屏幕宽
double height = screenSize.getHeight();//屏幕高
//设置frame居中
frame.setLocation((int) (width - frame.getWidth()) / 2, (int) (height - frame.getHeight()) / 2);
}
public void moveToCenter(JFrame frame) {
//先获得屏幕大小
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();//屏幕宽
double height = screenSize.getHeight();//屏幕高
//设置frame居中
frame.setLocation((int) (width - frame.getWidth()) / 2, (int) (height - frame.getHeight()) / 2);
}
我以前写窗口程序就是这么做的,不过现在好了,Window类中有一个方法:
public void setLocationRelativeTo(Component c)
该方法可以把窗体放在组件c的中间位置,如果组件c为null,则把窗体放在屏幕中央。下面是一个测试用例:
package javatest;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainTest extends JFrame {
public MainTest(String title) {
super(title);
JButton button = new JButton("点我可使窗口居中");
//给按键添加事件监听器
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//moveToCenter(MainTest.this);//使窗体居中
MainTest.this.setLocationRelativeTo(null);//使窗体居中
}
});
this.add(button);//按钮加入窗体中
this.setPreferredSize(new Dimension(300, 330));
this.pack();//布局管理器会根据prefferredSize来布局窗口大小
}
public static void main(String[] args) {
new MainTest("窗口居中").setVisible(true);
}
public void moveToCenter(JFrame frame) {
//先获得屏幕大小
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();//屏幕宽
double height = screenSize.getHeight();//屏幕高
//设置frame居中
frame.setLocation((int) (width - frame.getWidth()) / 2, (int) (height - frame.getHeight()) / 2);
}
}
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainTest extends JFrame {
public MainTest(String title) {
super(title);
JButton button = new JButton("点我可使窗口居中");
//给按键添加事件监听器
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//moveToCenter(MainTest.this);//使窗体居中
MainTest.this.setLocationRelativeTo(null);//使窗体居中
}
});
this.add(button);//按钮加入窗体中
this.setPreferredSize(new Dimension(300, 330));
this.pack();//布局管理器会根据prefferredSize来布局窗口大小
}
public static void main(String[] args) {
new MainTest("窗口居中").setVisible(true);
}
public void moveToCenter(JFrame frame) {
//先获得屏幕大小
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();//屏幕宽
double height = screenSize.getHeight();//屏幕高
//设置frame居中
frame.setLocation((int) (width - frame.getWidth()) / 2, (int) (height - frame.getHeight()) / 2);
}
}