资讯中心

有关监听器的使用步骤

📅 2026/8/16 12:24:41
有关监听器的使用步骤
序言在上篇笔记中通过使用图形化编程实现了登录界面的基础搭建但是不能实现注册与登录按钮的交互而监听器则是帮助我们实现该交互功能的重要工具因此在Java编程中监听器占据了重要的地位。什么是监听器监听器就是一个专门等着组件发生动作、动作一出现就自动执行对应代码的工具。它不会主动运行全程被动等待只有用户操作组件点按钮、输文字、勾选框才会触发。监听器的核心原理事件源如:按钮JButton当前动作发生的组件事件对象ActionEvent封装点击事件信息监听器接口ActionListener规范事件的处理方法注接口不能直接创建对象接口的使用步骤1.重新定义类实现接口2.重写接口中的抽象方法监听器实现类重写事件处理方法[actionPerformed()]绑定关系将监听器对象注册到事件源触发动作时自动执行监听器的任务监听器的使用步骤步骤1导入监听器相关头文件步骤2创建监听器实现ActionListener接口步骤3定义监听对象步骤4注册监听器步骤5在监听器重写方法中编写业务逻辑实战操作packagecom.sy.login0812;importjavax.swing.*;importjava.awt.*;publicclassLogin{publicvoidshowUI(){JFramejfnewJFrame();jf.setSize(400,600);jf.setTitle(登陆界面);jf.setLocationRelativeTo(null);jf.setDefaultCloseOperation(3);FlowLayoutflownewFlowLayout();jf.setLayout(flow);ImageIconimagenewImageIcon(C:\\Users\\PC\\Pictures\\Screenshots\\屏幕截图 2026-08-12 182435.png);JLabeljianewJLabel(image);jf.add(jia);JLabelusernewJLabel(账号);jf.add(user);JTextFieldjtfnewJTextField();DimensiondmnewDimension(330,30);jtf.setPreferredSize(dm);jf.add(jtf);JLabeluser1newJLabel(密码);jf.add(user1);JTextFieldjtf1newJTextField();Dimensiondm1newDimension(330,30);jtf1.setPreferredSize(dm1);jf.add(jtf1);JButtonjbunewJButton(登录);jf.add(jbu);ButtonListenerlistenernewButtonListener();jbu.addActionListener(listener);listener.userTextjtf;JButtonjbu1newJButton(注册);jf.add(jbu1);jbu.addActionListener(listener);listener.userText1jtf1;jf.setVisible(true);}publicstaticvoidmain(String[]args){LoginlonewLogin();lo.showUI();}}packagecom.sy.login0812;importjavax.swing.*;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;publicclassButtonListenerimplementsActionListener{publicStringname ;publicJTextFielduserText;publicStringname1Sylus0418;publicJTextFielduserText1;publicvoidactionPerformed(ActionEvente){StringuserNameuserText.getText();if(name.equals(userName)){JFramejf1newJFrame();jf1.setSize(200,300);jf1.setTitle(检验);jf1.setLocationRelativeTo(null);//居中显示jf1.setDefaultCloseOperation(3);JLabeluser2newJLabel(登陆成功);jf1.add(user2);jf1.setVisible(true);}else{JFramejf2newJFrame();jf2.setSize(200,300);jf2.setTitle(检验);jf2.setLocationRelativeTo(null);//居中显示jf2.setDefaultCloseOperation(3);JLabeluser3newJLabel(登陆失败);jf2.add(user3);jf2.setVisible(true);}StringuserName1userText1.getText();if(name1.equals(userName1)){JFramejf1newJFrame();jf1.setSize(200,300);jf1.setTitle(检验);jf1.setLocationRelativeTo(null);jf1.setDefaultCloseOperation(3);JLabeluser2newJLabel(登陆成功);jf1.add(user2);jf1.setVisible(true);}else{JFramejf2newJFrame();jf2.setSize(200,300);jf2.setTitle(检验);jf2.setLocationRelativeTo(null);jf2.setDefaultCloseOperation(3);JLabeluser3newJLabel(登陆失败);jf2.add(user3);jf2.setVisible(true);}}}运行结果个人收获总结通过本次对监听器学习我弄懂事件、事件源与监听类的配合逻辑掌握按钮绑定监听的完整流程能独立实现登录校验交互。