Java中监听器的使用步骤

📅 2026/8/8 10:39:53
Java中监听器的使用步骤
提示文章写完后目录可以自动生成如何生成可参考右边的帮助文档文章目录前言一、监听器要素二、补充:Java中的数据类型1.基本类型8个2.引用类型/自定义类型三、实现接口四、获取输入的数据完整实现前言本片笔记接上篇以登陆界面为例着重介绍Java中监听器的使用步骤。一、监听器要素1.事件源当前动作所发生的组件(swing)即登录按钮。2.监听器动作监听器方法即addActionListener()3.绑定事件处理类注意接口处不能直接创建对象需要重新写抽象方法二、补充:Java中的数据类型1.基本类型8个整型byte1字节 short2字节 int4字节 long8字节附1字节为8bit即2的8次方如byte范围为-2 7 2^727~2 7 2^727-1浮点型float单精度4字节 double双精度8字节字符char单个字符用单引号’表示布尔型boolean取值只有true和false2.引用类型/自定义类型如类class 接口interface 数组一种用来存储数据的数据结构其中类使用 new 创建对象接口身不能直接创建对象接口的使用2步1.重新定义类实现接口2.重写接口中的抽象方法抽象方法只有定义没有实现另自己定义的类也是一种数据类型三、实现接口实现接口的关键字implements实现接口public class 子类 implements 接口接口可以写多个实现接口一定要重写接口中的抽象方法publicvoidactionPerformed(ActionEvent e){}四、获取输入的数据获取输入框里用户输入的全部文本返回 String 字符串String userNameuserText.getText();把账号框对象jtf 传递给ButtonListener类即将界面文本框对象传入监听器点击按钮时监听器代码就能获取输入框里面的账号文本listener.userTextjtf;完整实现import ls.ButtonListener;import javax.swing.*;import java.awt.*;public class Login{public JTextField jtf;public JPasswordField jpf;publicvoidshowUI(){JFrame jfnewJFrame();jf.setSize(420,500);jf.setTitle(登录界面);jf.setLocationRelativeTo(null);jf.setDefaultCloseOperation(3);FlowLayout flownewFlowLayout();jf.setLayout(flow);ImageIcon imagenewImageIcon(C:\\Users\\Administrator\\Desktop\\微信图片_20260717080146_72_2);JLabel jlanewJLabel(image);jf.add(jla);JLabel usernewJLabel(账号:);jf.add(user);jtfnewJTextField();Dimension dmnewDimension(360,30);jtf.setPreferredSize(dm);jf.add(jtf);JLabel pwdLabelnewJLabel(密码:);jf.add(pwdLabel);jpfnewJPasswordField();jpf.setPreferredSize(dm);jf.add(jpf);JButton jbunewJButton(登录);jf.add(jbu);ButtonListener listennewButtonListener();jbu.addActionListener(listen);listen.usernameTextjtf;listen.passwordTextjpf;jf.setVisible(true);}publicstaticvoidmain(String[]args){Login lonewLogin();lo.showUI();}}package ls;import javax.swing.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class ButtonListener implements ActionListener{public String name123;public String pass123456;public JTextField usernameText;public JPasswordField passwordText;publicvoidactionPerformed(ActionEvent e){String usernameusernameText.getText();String passwordnewString(passwordText.getPassword());JFrame resultFramenewJFrame();resultFrame.setSize(300,180);resultFrame.setTitle(登录提示);resultFrame.setLocationRelativeTo(null);resultFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);JLabel tip;if(username.equals(name)password.equals(pass)){tipnewJLabel(登录成功);}else{tipnewJLabel(账号或密码错误登录失败);}resultFrame.add(tip);resultFrame.setVisible(true);}}