📄 testactionlistener.java
字号:
package UI;
import javax.swing.*;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.*;
public class TestActionListener implements ActionListener
{
JButton btnLogin=new JButton("Login");
JButton btnExit=new JButton("Exit");
JTextField txtName=new JTextField("");
JPasswordField txtPsw=new JPasswordField("");
JLabel l=new JLabel("用户名:",JLabel.RIGHT);
JLabel l1=new JLabel("口令:",JLabel.RIGHT);
JFrame frame;
public Component createComponents()
{
JPanel p=new JPanel(new GridLayout(3,2,4,4));
p.add(l);
p.add(txtName);
p.add(l1);
p.add(txtPsw);
p.add(btnLogin);
p.add(btnExit);
btnLogin.addActionListener(this);
btnLogin.setActionCommand("Login");
btnExit.addActionListener(this);
btnExit.setActionCommand("Exit");
return p;
}
public void actionPerformed(ActionEvent e)
{
String strName=txtName.getText();
String strPsw=txtPsw.getText();
String strMsg="您输入的用户名为:"+strName+"口令为:"+strPsw;
if(e.getActionCommand().equals("Login"))
{
JOptionPane.showMessageDialog(frame,strMsg);
if(strName.equals("admin")&&strPsw.equals("admin"))
{
strMsg="登录成功!!";
JOptionPane.showMessageDialog(frame,strMsg);
}else
{
strMsg="用户名或口令不正确!";
JOptionPane.showMessageDialog(frame,strMsg,"错误",JOptionPane.ERROR_MESSAGE);
}
}else
{
System.exit(0);
}
}
public static void main(String[] args)
{
TestActionListener t1=new TestActionListener();
t1.frame=new JFrame("行为事件事例窗口");
t1.frame.getContentPane().add(t1.createComponents());
t1.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t1.frame.setSize(300,100);
t1.frame.setVisible(true);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -