一、写在前面
1. 使用BoxLayout布局方式,控制组件内容在水平与垂直方向居中显示;
二、代码
public class LoginFrame extends JFrame {
private static final int LOGIN_WIDTH = 600;
private static final int LOGIN_HEIGHT = 400;
public LoginFrame(){
setTitle("登录界面");
JPanel loginPanel = new JPanel();
loginPanel.setBackground(new Color(204, 204, 204));//#CCC
loginPanel.setLayout(new BoxLayout(loginPanel, BoxLayout.Y_AXIS));
JPanel vCenterPanel = new JPanel();
vCenterPanel.setBackground(new Color(204, 204, 204));
vCenterPanel.setLayout(new BoxLayout(vCenterPanel, BoxLayout.X_AXIS));
JPanel hCenterPanel = new JPanel();
hCenterPanel.setBackground(Color.WHITE);
Box labelBox = Box.createVerticalBox();
JLabel jLabel = new JLabel("用户名:");
jLabel.setOpaque(true);
jLabel.setBackground(Color.YELLOW);
labelBox.add(jLabel);
labelBox.add(Box.createVerticalStrut(10));
JLabel label = new JLabel("密 码:");
label.setOpaque(true);
label.setBackground(Color.CYAN);
labelBox.add(label);
Box fieldBox = Box.createVerticalBox();
fieldBox.add(new JTextField(15));
fieldBox.add(Box.createVerticalStrut(10));
fieldBox.add(new JPasswordField(15));
Box hBox = Box.createHorizontalBox();
hBox.add(labelBox);
hBox.add(Box.createHorizontalStrut(15));
hBox.add(fieldBox);
Box vBox = Box.createVerticalBox();
vBox.add(Box.createVerticalStrut(50));
vBox.add(hBox);
vBox.add(Box.createVerticalStrut(10));
vBox.add(new JButton("登录"));
hCenterPanel.add(vBox);
vCenterPanel.add(Box.createHorizontalGlue());
vCenterPanel.add(hCenterPanel);
vCenterPanel.add(Box.createHorizontalGlue());
loginPanel.add(Box.createVerticalGlue());
loginPanel.add(vCenterPanel);
loginPanel.add(Box.createVerticalGlue());
getContentPane().add(loginPanel);
setSize(LOGIN_WIDTH, LOGIN_HEIGHT);
setLocation(Screen.getCenterPosition(LOGIN_WIDTH, LOGIN_HEIGHT));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new LoginFrame();
}
}
public class Screen {
private int width;
private int height;
public Screen(){
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
this.width = screenSize.width;
this.height = screenSize.height;
}
public static Point getCenterPosition(int width, int height){
Screen screen = new Screen();
int x = (screen.getWidth() - width) / 2;
int y = (screen.getHeight() - height) / 2;
return new Point(x, y);
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
三、效果图