Java AWT Event ActionListener
ActionListener in Java is a class that is responsible for 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 can also be used separately from the class by creating a new class that implements it. It should also be imported to your project. The method actionPerformed handles all the actions of a component, and inside this method, you will define or write your own codes that will be executed when an action occurred. Heres an example on how to implement ActionListener in Java. Implementing ActionListener in Javapackage 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; 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 UI will be: Explanation:
The next tutorial is about implementing a Mouse Listener that is used when we want to do something whenever a mouse hovers to the component and other actions. |