Event Handling trong java

5 minute read

IX. Xử lý sự kiện (Event Handling) trong Java:

A. Sự kiện và bộ xử lý sự kiện:

Trong Java, sự kiện là một hành động xảy ra trong một ứng dụng, chẳng hạn như bấm một nút, nhập từ bàn phím hoặc di chuyển chuột. Để xử lý sự kiện, bạn cần một bộ xử lý sự kiện.

  1. Sự kiện (Event):

    • Sự kiện là một hành động hoặc trạng thái thay đổi trong chương trình của bạn, ví dụ như bấm nút, nhấp chuột, hoặc nhập từ bàn phím.
    • Trong Java, mỗi loại sự kiện được biểu diễn bởi một lớp riêng.
  2. Bộ xử lý sự kiện (Event Listener):

    • Bộ xử lý sự kiện là một đối tượng có khả năng lắng nghe và xử lý các sự kiện xảy ra trong chương trình.
    • Trong Java, mỗi loại sự kiện cần một bộ xử lý sự kiện tương ứng để xử lý.
    • Bộ xử lý sự kiện cung cấp các phương thức để xử lý sự kiện khi nó xảy ra.
  3. Ví dụ về sự kiện và bộ xử lý sự kiện:

    • Trong giao diện đồ họa Swing của Java, bạn có thể sử dụng các lớp như ActionEvent, MouseListener, ActionListener, v.v. để xử lý sự kiện như nhấp chuột, bấm nút, v.v.

Ví dụ về sự kiện bấm nút và bộ xử lý sự kiện trong Java Swing:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import javax.swing.*;
import java.awt.event.*;

public class MainFrame extends JFrame {
    private JButton button;

    public MainFrame() {
        setTitle("Event Handling Example");
        setSize(300, 200);

        button = new JButton("Click Me");
        button.addActionListener(new ButtonClickListener());

        JPanel panel = new JPanel();
        panel.add(button);
        add(panel);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    private class ButtonClickListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(MainFrame.this, "Button clicked!");
        }
    }

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

Trong ví dụ trên, khi bạn nhấp vào nút, sự kiện ActionEvent được kích hoạt và ButtonClickListener sẽ được gọi để xử lý sự kiện này. Trong phương thức actionPerformed, chúng ta hiển thị một hộp thoại thông báo.

B. Xử lý sự kiện chuột và bàn phím:

Trong Java, để xử lý sự kiện chuột và bàn phím, bạn cần sử dụng các interface và lớp trong gói java.awt.event hoặc javax.swing.event. Dưới đây là cách xử lý sự kiện chuột và bàn phím trong Java:

  1. Xử lý sự kiện chuột:

    • Để xử lý sự kiện chuột, bạn cần sử dụng các interface như MouseListener, MouseMotionListener, MouseWheelListener.
    • Ví dụ về sự kiện nhấp chuột:
      1
      2
      3
      4
      5
      6
      7
      8
      
      import java.awt.event.*;
      
      public class MyMouseListener implements MouseListener {
          public void mouseClicked(MouseEvent e) {
              System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY());
          }
          // Implement các phương thức khác của MouseListener
      }
      
    • Để sử dụng bộ xử lý sự kiện chuột này, bạn cần gắn nó với một thành phần như JPanel hoặc JButton bằng cách sử dụng phương thức addMouseListener().
  2. Xử lý sự kiện bàn phím:

    • Để xử lý sự kiện bàn phím, bạn cần sử dụng các interface như KeyListener.
    • Ví dụ về sự kiện nhấn phím:
      1
      2
      3
      4
      5
      6
      7
      8
      
      import java.awt.event.*;
      
      public class MyKeyListener implements KeyListener {
          public void keyPressed(KeyEvent e) {
              System.out.println("Key pressed: " + e.getKeyChar());
          }
          // Implement các phương thức khác của KeyListener
      }
      
    • Tương tự, để sử dụng bộ xử lý sự kiện bàn phím này, bạn cần gắn nó với một thành phần như JPanel hoặc JTextField bằng cách sử dụng phương thức addKeyListener().
  3. Ví dụ tổng quát:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    
    import javax.swing.*;
    import java.awt.event.*;
    
    public class EventHandlingExample {
        public static void main(String[] args) {
            JFrame frame = new JFrame("Event Handling Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            JPanel panel = new JPanel();
            JButton button = new JButton("Click Me");
            JTextField textField = new JTextField(20);
    
            button.addMouseListener(new MyMouseListener());
            textField.addKeyListener(new MyKeyListener());
    
            panel.add(button);
            panel.add(textField);
            frame.add(panel);
    
            frame.setSize(300, 200);
            frame.setVisible(true);
        }
    }
    
    class MyMouseListener extends MouseAdapter {
        public void mouseClicked(MouseEvent e) {
            System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY());
        }
    }
    
    class MyKeyListener extends KeyAdapter {
        public void keyPressed(KeyEvent e) {
            System.out.println("Key pressed: " + e.getKeyChar());
        }
    }
    

Trong ví dụ trên, chúng ta sử dụng MouseListener để xử lý sự kiện chuột khi nhấp chuột vào nút, và sử dụng KeyListener để xử lý sự kiện bàn phím khi nhập văn bản vào ô văn bản.

C. Sử dụng ActionListener và WindowListener:

Trong Java, ActionListenerWindowListener là hai interface quan trọng được sử dụng để xử lý sự kiện liên quan đến các thành phần giao diện người dùng và cửa sổ ứng dụng. Dưới đây là cách sử dụng chúng:

  1. ActionListener:

    • ActionListener được sử dụng để xử lý sự kiện khi một hành động được thực hiện trên một thành phần như JButton, JMenuItem, v.v.
    • Interface này chứa một phương thức actionPerformed(ActionEvent e) cần được triển khai.
    • Ví dụ:
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      
      import javax.swing.*;
      import java.awt.event.*;
      
      public class MyButtonFrame extends JFrame {
          private JButton button;
      
          public MyButtonFrame() {
              setTitle("ActionListener Example");
              setSize(300, 200);
      
              button = new JButton("Click Me");
              button.addActionListener(new MyActionListener());
      
              JPanel panel = new JPanel();
              panel.add(button);
              add(panel);
      
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
          }
      
          private class MyActionListener implements ActionListener {
              public void actionPerformed(ActionEvent e) {
                  JOptionPane.showMessageDialog(MyButtonFrame.this, "Button clicked!");
              }
          }
      
          public static void main(String[] args) {
              new MyButtonFrame();
          }
      }
      
  2. WindowListener:

    • WindowListener được sử dụng để xử lý sự kiện liên quan đến cửa sổ, như mở, đóng, hoặc thay đổi kích thước.
    • Interface này chứa một loạt các phương thức như windowOpened(WindowEvent e), windowClosed(WindowEvent e), v.v.
    • Ví dụ:
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      
      import javax.swing.*;
      import java.awt.event.*;
      
      public class MyWindowFrame extends JFrame {
          public MyWindowFrame() {
              setTitle("WindowListener Example");
              setSize(300, 200);
      
              addWindowListener(new MyWindowListener());
      
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
          }
      
          private class MyWindowListener implements WindowListener {
              public void windowOpened(WindowEvent e) {
                  System.out.println("Window opened");
              }
      
              // Implement các phương thức khác của WindowListener
              public void windowClosed(WindowEvent e) {}
              public void windowClosing(WindowEvent e) {}
              public void windowIconified(WindowEvent e) {}
              public void windowDeiconified(WindowEvent e) {}
              public void windowActivated(WindowEvent e) {}
              public void windowDeactivated(WindowEvent e) {}
          }
      
          public static void main(String[] args) {
              new MyWindowFrame();
          }
      }
      

Trong cả hai ví dụ trên, chúng ta sử dụng addActionListener()addWindowListener() để gắn các bộ xử lý sự kiện với JButton và JFrame tương ứng. Điều này cho phép chúng ta xử lý sự kiện khi người dùng thực hiện hành động trên các thành phần hoặc tương tác với cửa sổ ứng dụng.