事件监听器

《零基础学Java》


  • 事件监听器

    为按钮等添加事件监听器,事件监听器的作用是在用户单击按钮时,设置窗体要实现的功能。

  • 动作事件监听器

动作事件监听器(AbstractAction)监听器是Swing中比较常用的事件监听器,很多最近的动作都会使用它监听(比如:按钮被单击)。

动作事件监听器

动作事件监听器 实例

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

public class Demo17 extends JFrame {
    public Demo17(){
        setBounds(100,100,300,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        Container c = getContentPane();
        c.setLayout(new FlowLayout());

        JLabel jLabel = new JLabel("标签");
        c.add(jLabel);

        /**
         * 为 按钮 添加动作监听
         */
        JButton jButton = new JButton("按钮");
        jButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jLabel.setText("按钮被点击");
            }
        });
        c.add(jButton);

        /**
         * 为 文本框 添加动作监听
         */
        JTextField jTextField = new JTextField(10);
        c.add(jTextField);
        jTextField.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Object obj = e.getSource();//捕捉这个动作由那个按键触发的
                JTextField jTextField1 = (JTextField)obj;
                System.out.println(jTextField1.getText());

                jLabel.setText("文本框中点击了回车");
            }
        });

        /**
         * 为 多选框 添加动作监听
         */
        JCheckBox jCheckBox = new JCheckBox("多选框");
        c.add(jCheckBox);
        jCheckBox.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jLabel.setText("多选框被点击");
            }
        });

        /**
         * 为 单选框 添加动作监听
         */
        JRadioButton jRadioButton = new JRadioButton("单选框");
        c.add(jRadioButton);
        jRadioButton.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jLabel.setText("单选框被点击");
            }
        });

        /**
         * 为 下拉列表 添加动作监听
         */
        String string[] = {"选项1","选项2"};
        JComboBox jComboBox = new JComboBox(string);
        c.add(jComboBox);
        jComboBox.addActionListener(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jLabel.setText("下拉列表被选择");
            }
        });

        setVisible(true);
    }

    public static void main(String[] args) {
        new Demo17();
    }
}

动作事件监听器 实例输出结果:

  • 键盘事件

    当向文本框中输入文本内容时,将触发键盘事件。KeyEvent类 负责捕获键盘事件,可以通过为组
    件添加实现了 KeyListener接口 的监听器类,来处理该组件触发的键盘事件。

    KeyListener接口的三个方法:

    keyListener.addKeyListener(new KeyListener() {
                @Override
                public void keyTyped(KeyEvent e) {
    			//发生击键事件时触发
                }
    
                @Override
                public void keyPressed(KeyEvent e) {
    			//按键被按下时触发
                }
    
                @Override
                public void keyReleased(KeyEvent e) {
                //按键被释放时触发
                }
            });
    

    KeyListener类的常用方法:

(PS:在 KeyEvent类 中以 “VK_” 开头的静态常量代表各个按键的 keyCode,可以通过这些
静态常量判断事件中的按键,获得按键的标签。)

键盘事件 实例:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class LoginAuthentication extends JFrame {

    private JPanel jPanel1;
    private JPanel jPanel2;
    private JTextField account;
    private JPasswordField password;
    private JButton jButton;
    private String zh = "123";
    private String mm = "456";

    public LoginAuthentication() {
        setBounds(100, 100, 320, 230);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("目前状态:正在登录中");

        Container c = getContentPane();
        c.setLayout(new FlowLayout());

        jPanel1 = new JPanel(new FlowLayout());
        jPanel1.setBorder(BorderFactory.createTitledBorder("账号"));
        account = new JTextField(20);
        account.addKeyListener(new KeyListener() {//创建键盘事件
            @Override
            public void keyTyped(KeyEvent e) {

            }

            @Override
            public void keyPressed(KeyEvent e) {

            }

            @Override
            public void keyReleased(KeyEvent e) {
                int dl = e.getKeyCode();
                switch (dl) {
                    case KeyEvent.VK_ENTER:
                        password.requestFocus();
                        return;
                }
            }
        });
        jPanel1.add(account);
        c.add(jPanel1);

        jPanel2 = new JPanel(new FlowLayout());
        jPanel2.setBorder(BorderFactory.createTitledBorder("密码"));
        password = new JPasswordField(20);
        jPanel2.add(password);
        c.add(jPanel2);

        jButton = new JButton("登录");
        jButton.addActionListener(new AbstractAction() {//创建鼠标事件
            @Override
            public void actionPerformed(ActionEvent e) {
                if (account.getText().equals(zh)) {
                    char ch[] = password.getPassword();
                    String zhu = new String(ch);
                    if (zhu.equals(mm)) {
                        System.out.println("登录成功");
                        setTitle("目前状态:登录成功");
                    }else{
                        System.out.println("登录失败");
                        setTitle("目前状态:登录失败");
                    }
                }else {
                    System.out.println("登录失败");
                    setTitle("目前状态:登录失败");
                }
            }
        });
        c.add(jButton);

        setVisible(true);
    }

    public static void main(String[] args) {
        new LoginAuthentication();
    }
}

键盘事件 实例输出结果:

  • 鼠标事件

    所有组件都能应用鼠标事件, MouseEvent类 负责捕获鼠标事件,可以通过为组件添加实现了
    MouseListener接口的监听器类来处理该组件触发的鼠标事件。MouseListener接口 共有5个抽象方法,分别在光标移入光标移出鼠标按键被按下鼠标按键被释放鼠标按键被单击 事件时被触发。

    MouseListener接口的五个方法:

 clickArea.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                //鼠标点击
            }

            @Override
            public void mousePressed(MouseEvent e) {
				//按键按下
            }

            @Override
            public void mouseReleased(MouseEvent e) {
				//按键释放
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                //鼠标进入
            }

            @Override
            public void mouseExited(MouseEvent e) {
         		//鼠标退出
            }
        });

MouseEvent类的常用方法:

MouseEvent类中代表鼠标按键的静态常量:

鼠标事件 实例:

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class Demo19 extends JFrame {
    private JScrollPane jScrollPane;
    private JTextArea out;
    private JPanel promptArea;
    private JPanel clickArea;

    public Demo19(){
        setBounds(100,100,450,400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("鼠标事件");

        Container c =getContentPane();
        c.setLayout(new GridLayout(1,2));

        promptArea=new JPanel(new FlowLayout());
        promptArea.setBorder(BorderFactory.createTitledBorder("输出区域"));
        out=new JTextArea("",18,18);
        jScrollPane=new JScrollPane(out);
        promptArea.add(jScrollPane);
        c.add(promptArea);

        clickArea=new JPanel(new FlowLayout());
        clickArea.setBorder(BorderFactory.createTitledBorder("点击区域"));
        clickArea.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {//鼠标点击
                int hitCount = e.getClickCount();//鼠标点击次数
                int clickButton = e.getButton();//鼠标点击的按键
                switch (clickButton){
                    case MouseEvent.BUTTON1:
                        out.append("鼠标左键点击了"+hitCount+"次组件\n");
                        break;
                    case MouseEvent.BUTTON2:
                        out.append("鼠标中键点击了"+hitCount+"次组件\n");
                        break;
                    case MouseEvent.BUTTON3:
                        out.append("鼠标右键点击了"+hitCount+"次组件\n");
                        break;
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {//按键按下

            }

            @Override
            public void mouseReleased(MouseEvent e) {//按键释放

            }

            @Override
            public void mouseEntered(MouseEvent e) {//鼠标进入
                out.append("鼠标进入组件\n");
            }

            @Override
            public void mouseExited(MouseEvent e) {//鼠标退出
                out.append("鼠标退出组件\n");
            }
        });
        c.add(clickArea);




        setVisible(true);
    }

    public static void main(String[] args) {
        new Demo19();
    }
}

鼠标事件 实例输出结果:

  • 窗体事件

    WindowListener接口中五个方法:

    public DemoWindw(){
            addWindowListener(new MywindowListener());//创建窗体事件监听
        }
    
    class MywindowListener implements WindowListener{
    
            @Override
            public void windowOpened(WindowEvent e) { 
              	//窗体打开
            }
    
            @Override
            public void windowClosing(WindowEvent e) {
                //窗体将要关闭
            }
    
            @Override
            public void windowClosed(WindowEvent e) {
                //窗体已经关闭
            }
    
            @Override
            public void windowIconified(WindowEvent e) {
                //窗体最小化
            }
    
            @Override
            public void windowDeiconified(WindowEvent e) {
                //窗体恢复正常大小
            }
    
            @Override
            public void windowActivated(WindowEvent e) {
                //窗体激活
            }
    
            @Override
            public void windowDeactivated(WindowEvent e) {
                //窗体失去激活
            }
        }
    

    窗体事件 实例:

    import javax.swing.*;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    
    public class Demo20 extends JFrame {
        public Demo20(){
            setBounds(100,100,300,300);
            /**
             * EXIT_ON_CLOSE:关闭窗口同时停止程序
             * DISPOSE_ON_CLOSE:关闭窗口时释放窗体资源
             */
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            setVisible(true);
    
            addWindowListener(new MywindowListener());//创建窗体事件监听
        }
    
        class MywindowListener implements WindowListener{
    
            @Override
            public void windowOpened(WindowEvent e) { //窗体打开
                System.out.println("窗体被打开");
            }
    
            @Override
            public void windowClosing(WindowEvent e) {//窗体将要关闭
                System.out.println("窗体将要被关闭");
            }
    
            @Override
            public void windowClosed(WindowEvent e) {//窗体已经关闭
                /**
                 * 如果使用EXIT_ON_CLOSE(关闭窗口同时停止程序)可能无法触发此方法
                 */
                System.out.println("窗体已经被关闭");
            }
    
            @Override
            public void windowIconified(WindowEvent e) {//窗体最小化
                System.out.println("窗体最小化");
            }
    
            @Override
            public void windowDeiconified(WindowEvent e) {//窗体恢复正常大小
                System.out.println("窗体恢复正常大小");
            }
    
            @Override
            public void windowActivated(WindowEvent e) {//窗体激活
                System.out.println("窗体被激活");
            }
    
            @Override
            public void windowDeactivated(WindowEvent e) {//窗体失去激活
                System.out.println("窗体失去激活");
            }
        }
    
        public static void main(String[] args) {
            new Demo20();
        }
    }
    

    窗体事件 实例输出结果:

posted on 2022-04-03 14:33  TeaTracing  阅读(849)  评论(0编辑  收藏  举报