我想让界面更漂亮,因为JPanel p1里面的组件太大了。我的声誉不足以让我放置图像,所以我只显示我的源代码。我想这样做:
public class TestFrame extends JFrame{
private JButton b1 = new JButton("登陆"),b2 = new JButton("注册");
private JTextField userName = new JTextField(),password = new JTextField();
public TestFrame(){
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(2,2,10,10));
p1.add(new JLabel("用户名:"));
p1.add(userName);
p1.add(new JLabel("密码:"));
p1.add(password);
JPanel p2 = new JPanel();
p2.add(b1);
p2.add(b2);
add(p1,BorderLayout.CENTER);
add(p2,BorderLayout.SOUTH);
b1.addActionListener(new ButtonListener());
b2.addActionListener(new ButtonListener());
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == b2){
if (userName.getText().equals("") || password.getText().equals("")){
System.out.println("用户名和密码不能为空");
}
else if (User.getCount() == 0){
User.setUserName(userName.getText());
Password.setPassword(password.getText());
System.out.println("succeed");
}
else if (User.isUserName(userName.getText())){
System.out.println("用户名已存在");
}
else {
User.setUserName(userName.getText());
Password.setPassword(password.getText());
System.out.println("succeed");
}
}
if (e.getSource() == b1){
if (User.isUserName(userName.getText()) && Password.isPassword(userName.getText(),password.getText())){
System.out.println("登陆成功");
System.exit(0);
}
else System.out.println("登陆失败");
}
}
}
public static void main(String[] args){
TestFrame frame = new TestFrame();
frame.setTitle("欢迎");
frame.setSize(400,300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
答案 0 :(得分:2)
而不是frame.setSize(400,300);
调用frame.pack()
,而是根据您的组件设置框架的大小。