• ActionListener

    ActionListener is a class that is responsible in handling all action events such as when the user clicks on a component. Mostly, action listeners are used for JButtons. An ActionListener can be used by the implements keyword to the class definition. It should also be imported to your project. The method actionPerformed handles the all the actions, and also here, you will defined or write your own codes what will happened when an action occured. For example:

    package com.javapointers.javase;
    
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    
    /**
     *
     * @author javapointers
     */
    public class ActionListenerTest implements ActionListener {
    
        JButton button;
        JFrame frame;
        JTextArea textArea;
    
        public ActionListenerTest() {
            button = new JButton("Click Me");
            frame = new JFrame("ActionListener Test");
            textArea = new JTextArea(5, 40);
    
            button.addActionListener(this);
            textArea.setLineWrap(true);
            frame.setLayout(new BorderLayout());
            frame.add(textArea, BorderLayout.NORTH);
            frame.add(button, BorderLayout.SOUTH);
            frame.pack();
    
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            textArea.setText(textArea.getText().concat("You have clicked
            the button\n"));
        }
    
        public static void main(String args[]) {
            ActionListenerTest test = new ActionListenerTest();
        }
    }
    
    

    when we run our program, the output will be:

    Explanation:

    • public class ActionListenerTest implements ActionListener {

      an action listener should be implemented in a class before you can use it. Just add the implements keyword and the listener.

    • button.addActionListener(this);

      means that the component button will be added to the components that are being tracked for action event. A component should be  be added an action listener so that you can add codes whenever a user click that component. A component that is not added with an action listener will not be monitored.

    • public void actionPerformed(ActionEvent e) {}

      this method is already defined in ActionListener class and we have just override it. Here, you will defined what will your program do when the user click the component being monitored for an action event.

      
      

    Related Post