展开全部
给按钮添加事件响应器,当点击按钮才62616964757a686964616fe78988e69d8331333363393035执行去数据库查询. 参考代码import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LogDemo extends JFrame implements ActionListener{
JTextField jtf;//用户名
JPasswordField jpf;//密码
JButton jb1;
public LogDemo() {
JPanel jp = new JPanel(new GridLayout(2, 1));
JPanel jp1 = new JPanel();
JLabel jl1 = new JLabel("用户名");
jtf = new JTextField(15);
jp1.add(jl1);
jp1.add(jtf);
jp.add(jp1);
JPanel jp2 = new JPanel();
JLabel jl2 = new JLabel("密 码");
jpf = new JPasswordField(15);
jp2.add(jl2);
jp2.add(jpf);
jp.add(jp2);
add(jp);
JPanel jp3 = new JPanel();
jb1 = new JButton("登陆");
jb1.addActionListener(this);//因为LogDemo窗口实现了ActionListener接口,所以参数就填写this
jp3.add(jb1);
add(jp3,BorderLayout.SOUTH);
setTitle("Demo");// 标题
setResizable(false);
setSize(320, 150);// 窗口大小
setLocationRelativeTo(null);// 窗口居中
setDefaultCloseOperation(EXIT_ON_CLOSE);// 窗口点击关闭时,退出程序
}
public static void main(String[] args) {
new LogDemo().setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(jb1==e.getSource()) { //判断是不是登陆按钮被点击了
System.out.println("点击了登陆");
String name = jtf.getText();//获得用户名
String pswd = new String(jpf.getPassword());//获得密码
//这里可以使用b数据库去 验证用户名和密码. 如果验证成功返回true,失败返回false
if(name.equals("admin")&&pswd.equals("123")) {
System.out.println("登陆成功");
JOptionPane.showMessageDialog(this, "登陆成功");
}else {
System.out.println("登陆失败");
jtf.setText("");//清空用户名框
jpf.setText("");//清空密码框
JOptionPane.showMessageDialog(this, "登陆失败");
}
}
}
}