JButton in Java Swing example

1
Adding a action listener to button import javax.swing.JButton; import javax.swing.JFrame; import java.awt.event.ActionListener; import java.awt.Component; import java.awt.event.ActionEvent; import javax.swing.JOptionPane; import javax.swing.JPanel; public class action_listner_implementation extends JFrame { action_listner_implementation() { setSize(200, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button1 = new JButton("Message dialog"); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog((Component) e.getSource(), "Thank you!");}}); JPanel jp=new JPanel(); jp.add(button1); getContentPane().add(jp); } public static void main(String[] args) { action_listner_implementation a=new action_listner_implementation(); a.setVisible(true); } }

Transcript of JButton in Java Swing example

Page 1: JButton in Java Swing example

Adding a action listener to button

import javax.swing.JButton;import javax.swing.JFrame;import java.awt.event.ActionListener;import java.awt.Component;import java.awt.event.ActionEvent;import javax.swing.JOptionPane;import javax.swing.JPanel;public class action_listner_implementation extends JFrame {

action_listner_implementation(){ setSize(200, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button1 = new JButton("Message dialog"); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog((Component) e.getSource(), "Thank

you!");}}); JPanel jp=new JPanel(); jp.add(button1); getContentPane().add(jp);}public static void main(String[] args) {

action_listner_implementation a=new action_listner_implementation();a.setVisible(true);

}}