JAVA学习笔记(二)
这星期通过学习了异常处理和事件监听,在程序中也能实现,不过功能不是很好。主要做了个单选框,添加事件响应,但做出来的时候界面不能直接显示出那些按钮以及标签,必须拖动一下界面大小才能显示出来,希望老师可以帮助解决一下。
package 登录界面;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class Login {
private JFrame frame;
public Login()
{
makeFrame();
}
private void makeFrame() {
final String userName = "2014330331";
final String passwrod = "1";
frame = new JFrame("Login");
Container contentPane = frame.getContentPane();
JLabel fileLabel = new JLabel("welcome to visit");
contentPane.add(fileLabel,BorderLayout.NORTH);
JLabel statusLabel = new JLabel("Version 2016");
contentPane.add(statusLabel,BorderLayout.SOUTH);
frame.pack();
frame.setSize(500, 300);
frame.setVisible(true);
//关闭窗口结束进程
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//确定界面的组件的布局
JPanel westPanel = new JPanel (new FlowLayout(FlowLayout.CENTER));
JPanel inwestPanel = new JPanel(new GridLayout(4,1));
westPanel.add(inwestPanel);
contentPane.add(westPanel,BorderLayout.CENTER);
//添加组件以及事件监听
JLabel l1 = new JLabel("账号");
JLabel l2 = new JLabel("密码");
JTextField t1 = new JTextField(15);
JPasswordField t2 =new JPasswordField(15);
JCheckBox c1 = new JCheckBox("记住密码");
JCheckBox c2 = new JCheckBox("自动登录");
JButton b1 = new JButton("登录");
b1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(userName.equals(t1.getText()) && passwrod.equals(t2.getText())) {
JOptionPane.showMessageDialog(null, "登陆成功", "提示", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "错误", "提示", JOptionPane.ERROR_MESSAGE);
t1.setText("");
t2.setText("");
}
}
});
JButton b2 = new JButton("退出");
JPanel p1 = new JPanel();
p1.add(l1);
p1.add(t1);
inwestPanel.add(p1);
JPanel p2 = new JPanel();
p2.add(l2);
p2.add(t2);
inwestPanel.add(p2);
JPanel p3 = new JPanel();
p3.add(c1);
p3.add(c2);
inwestPanel.add(p3);
JPanel p4 = new JPanel();
p4.add(b1);
p4.add(b2);
inwestPanel.add(p4);
//将窗口放在屏幕中央
int windowWidth = frame.getWidth();
int windowHeight = frame.getHeight();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
frame.setLocation(screenWidth/2-windowWidth/2, screenHeight/2-windowHeight/2);
}
public void panel(){
}
public static void main(String[] args){
// TODO Auto-generated method stub
new Login();
}
}