我用jbuild做的java swing开发,但是窗口无法居中了。
代码如下:
Toolkit tk=Toolkit.getDefaultToolkit();
Dimension d=tk.getScreenSize();
int screenHeight=d.height;
int screenWidth=d.width;
f.setSize(x,y);
f.setLocation((screenWidth-x)/2,(screenHeight-y)/2);
f.show();
代码如下:
Toolkit tk=Toolkit.getDefaultToolkit();
Dimension d=tk.getScreenSize();
int screenHeight=d.height;
int screenWidth=d.width;
f.setSize(x,y);
f.setLocation((screenWidth-x)/2,(screenHeight-y)/2);
f.show();
//调整显示位置
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension tempSize = testframe.getSize();
if (tempSize.height > screenSize.height)
{
tempSize.height = screenSize.height;
}
if (tempSize.width > screenSize.width)
{
tempSize.width = screenSize.width;
}
testframe.setLocation((screenSize.width - tempSize.width) / 2, (screenSize.height - tempSize.height) / 2);
testframe.show();
首先要通过Toolkit获取你的屏幕的窗口的长度和宽度,在通过计算给窗口定位,4楼的很详细了
package swing;import java.awt.*;import javax.swing.*;import java.awt.event.*;
import java.net.URL;
import java.sql.*;public class LogOn extends JFrame {
public static LogOn logon;
private JLabel usernameLabel, passwordLabel;
private JTextField usernameText;
private JPasswordField passwordText;
private JButton cancelButton, confButton; public LogOn() { getContentPane().setForeground(Color.WHITE);
setSize(400, 200);
((JPanel) getContentPane()).setOpaque(false);
double lx = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
double ly = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
this.setLocation(new Point((int) (lx / 2) -200, (int) (ly / 2) - 200));// 设定窗口出现位置
Container container = getContentPane();
container.setBackground(Color.WHITE);
container.setLayout(null);
usernameLabel = new JLabel("用户名:", JLabel.RIGHT);
passwordLabel = new JLabel("密 码:", JLabel.RIGHT);
usernameText = new JTextField(10);
passwordText = new JPasswordField(10);
cancelButton = new JButton(" 退出");
confButton = new JButton("确定"); usernameLabel.setBounds(80, 50, 50, 25);
usernameText.setBounds(130, 50, 80, 20); passwordLabel.setBounds(80, 80, 50, 25);
passwordText.setBounds(130, 80, 80, 20);
cancelButton.setBounds(250, 80, 80, 20);
confButton.setBounds(250, 50, 80, 20); container.add(usernameLabel);
container.add(usernameText);
container.add(passwordLabel);
container.add(passwordText);
container.add(cancelButton);
container.add(confButton); cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
} });
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String arguments[]) {
LogOn application = new LogOn();
}
}