How to Implement JButton.addActionListener() Method in Java Example
Adding JButton actionListener.
Run below code.
[
import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.UIManager; import javax.swing.JOptionPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class JButtonAddActionListener extends JPanel { public JTextField field; public JButton button; public JButtonAddActionListener() { field=new JTextField("Enter name"); button=new JButton("Click me"); button.addActionListener(new ButtonActionListener() ); add(field); add(button); } public static void main(String args[]) { JFrame f=new JFrame("Simple Action Listener program example"); f.getContentPane().add(new JButtonAddActionListener () ); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(400,400); f.setLocationRelativeTo(null); f.setVisible(true); } class ButtonActionListener implements ActionListener { ButtonActionListener() { } @Override public void actionPerformed(ActionEvent e) { String text=field.getText(); JOptionPane.showMessageDialog(null,"Message entered is \n" +text, "Action Listener Example", JOptionPane.INFORMATION_MESSAGE); throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } }
]
Result:
JButton.addActionListener() Code Explanation
In this article have introduced more swing components i.e
- JPanel
- JOptionPane
Others are JFrame methods.
- f.getContentPane().add(new JButtonAddActionListener () )-adds the JPanel to JFrame
- new JButtonAddActionListener ()-creates a new JButtonAddActionListener() class.
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)-closes the JFrame window when X button is clicked and exits the program
- f.setSize(400,400)-sets the window size.
- f.setLocationRelativeTo(null)-positions the JFrame window at the center of the screen
- f.setVisible(true)-displays the JFrame window.
class ButtonActionListener is a inner class that has access to public variables of the outer class and that the reason why we can be able to getText() entered in JTextField field
To read more about JButton and ActionListener classes check below Javadoc documents.
JButton
ActionListener