商苑面馆:用户登录界面功能实现
来自CloudWiki
(重定向自Java任务:用户登录界面功能实现)
目录
任务描述
完善用户登录界面功能:
登录成功时,弹出成功界面,如图:
失败时,弹出失败界面,如图:
基本实现
创建窗体
具体代码可见 Java任务:购书系统登录窗体的设计
观察有什么事件需要处理
在上述窗体中,有什么事件需要处理呢?
很显然,这个窗体很简单,只有两个按钮的点击事件需要处理。
由前面的知识知道,点击按钮所触发的事件是ActionEvent
我们需要处理ActionEvent事件。
创建事件监听器
接着为其建立监听器。共有两个监听器:一个是登陆按钮的监听器,一个是重置按钮的监听器。
LoginAction:
private class LoginAction implements ActionListener{ public LoginAction(){ } @Override public void actionPerformed(ActionEvent e) { // 获取用户输入的账号和密码 String uid = txtUserID.getText(); String pwd = new String(txtPassword.getPassword()); JOptionPane.showMessageDialog(null, uid+","+pwd, "信息", JOptionPane.INFORMATION_MESSAGE); } }
ResetAction:
private class ResetAction implements ActionListener{ public ResetAction(){ } @Override public void actionPerformed(ActionEvent e) { txtUserID.setText(""); txtPassword.setText(""); txtUserID.requestFocus(); } }
绑定事件监听器
btnLogon.addActionListener(new LoginAction()); btnSet.addActionListener(new ResetAction());
写一个main方法,测试运行
public static void main(String[] args) { UserInfo userInfo=new UserInfo(); }
简化实现(Lambda表达式)
在学了Lambda表达式,上述代码还可以这样写,不用单独定义事件监听器了,直接写一个匿名的表达式:
package main; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class UserForm extends JFrame{ private JLabel labelUser=new JLabel("用户登录",JLabel.CENTER); private JLabel labelPwd= new JLabel("登录密码",JLabel.CENTER);//“登录密码”标签 private JTextField txtUserID = new JTextField(16);//“登录账号”文本框 private JPasswordField txtPassword=new JPasswordField(16);//密码框 private JLabel labelUser2=new JLabel("@126.com",JLabel.CENTER); private JButton btnLogon =new JButton("登陆");//登录按钮 private JButton btnReset = new JButton("重置");//重置按钮 public UserForm() { this.setTitle("商苑面馆-用户登陆"); //A.创建第一个面板,内部采用网格布局,在其中添加用户登录、用户密码控件 JPanel centerPane=new JPanel(); centerPane.setLayout(new GridLayout(2,2));//步骤1:创建网格布局 centerPane.add(labelUser);//步骤2:将组件添加到面板上 centerPane.add(txtUserID); centerPane.add(labelPwd); centerPane.add(txtPassword); this.add(centerPane, BorderLayout.CENTER); //步骤3:以边界布局的方式,将面板整体添加到框架上 //B.创建第二个面板,内部采用流式布局,在其中添加用户登录和重置按钮 JPanel southPane=new JPanel(); southPane.setLayout(new FlowLayout()); southPane.add(btnLogon); southPane.add(btnReset); //直接用lambda表达式写事件监听器,点击登陆按钮之后显示信息 btnLogon.addActionListener(e ->{ String uid = txtUserID.getText(); String pwd = new String(txtPassword.getPassword()); JOptionPane.showMessageDialog(null, uid+","+pwd, "信息", JOptionPane.INFORMATION_MESSAGE); }); //直接用lambda表达式写事件监听器,点击登陆按钮之后显示信息 btnReset.addActionListener(e ->{ txtUserID.setText(""); txtPassword.setText(""); txtUserID.requestFocus(); }); this.add(southPane,BorderLayout.SOUTH); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(300,150); this.setVisible(true); this.setLayout(new BorderLayout());//为框架上的面板设立布局方式,设为边界布局 this.setLocationRelativeTo(null);//将窗口设为中央 } public static void main(String[] args) { // TODO Auto-generated method stub UserForm userForm=new UserForm(); } }
返回 Java程序设计