事件模型
代码实测登录窗口
package test;
import javax.swing.JFrame;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.*;
public class actionevent {
public static void main(String[] args)
{
action frame=new action();
}
}
class action extends JFrame implements ActionListener
{
JButton b1=new JButton("登录");
JButton b2=new JButton("取消");
JTextField t1=new JTextField(15);
JTextField t2=new JTextField(15);
JLabel l1=new JLabel("用户账号");
JLabel l2=new JLabel("登录密码");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JPanel p4=new JPanel();
action()
{
this.setSize(300,200);
Container container=this.getContentPane();
FlowLayout fleft=new FlowLayout(FlowLayout.CENTER,10,10);
FlowLayout fright=new FlowLayout(FlowLayout.RIGHT,10,10);
BorderLayout border=new BorderLayout(10,10);
GridLayout g=new GridLayout(2,1);
container.setLayout(border);
p1.setLayout(fleft);
p2.setLayout(fleft);
p3.setLayout(fright);
p4.setLayout(g);
p1.add(l1);
p1.add(t1);
p2.add(l2);
p2.add(t2);
p3.add(b1);
p3.add(b2);
p4.add(p1);
p4.add(p2);
container.add(p4, BorderLayout.CENTER);
container.add(p3, BorderLayout.SOUTH);
b1.addActionListener((ActionListener) this);
b2.addActionListener((ActionListener) this);
this.setTitle("面板应用");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==b1)
{
if(t1.getText().equals("admin"))
{
if(t2.getText().equals("111"))
{
JOptionPane.showMessageDialog(this,"恭喜你登陆成功","系统消息",JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(this,"密码错误","系统消息",JOptionPane.INFORMATION_MESSAGE);
t2.setText("");
}
}
else
{
JOptionPane.showMessageDialog(this,"用户名错误,重新登陆","系统消息",JOptionPane.INFORMATION_MESSAGE);
t2.setText("");
t1.setText("");
}
}
else if(e.getSource()==b2)
{
t2.setText("");
t1.setText("");
}
}
}