import java.awt.*; import java.awt.event.*; // for ActionListener import javax.swing.*; public class SimpleButtonExample // to demonstrate the use of JButtons { public static void main(String[] args) { JFrame frame=new JFrame("simple button example"); frame.setSize(300,200); ButtonExample p=new ButtonExample(); frame.add(p); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public static class ButtonExample extends JPanel implements ActionListener // ActionListener for JButtons { private JButton b1, b2, b3, clear, quit; // 5 JButtons, first three display a new message, fourth clears message, fifth quits private JLabel lab; // for output of the message public ButtonExample() { b1=new JButton("button 1"); // instantiate the 5 JButtons and JLabel b2=new JButton("button 2"); b3=new JButton("button 3"); clear=new JButton("clear"); quit=new JButton("quit"); lab=new JLabel(" "); b1.addActionListener(this); // use this class to implement the ActionListener for all 5 JButtons b2.addActionListener(this); b3.addActionListener(this); clear.addActionListener(this); quit.addActionListener(this); JPanel p1=new JPanel(new GridLayout(3,2)); // place the 5 JButtons and JLabel in a 3x2 grid p1.add(b1); p1.add(b2); p1.add(b3); p1.add(clear); p1.add(quit); p1.add(lab); add(p1); // place the 3x2 grid in this JPanel } public void actionPerformed(ActionEvent e) // will be called whenever a JButton is clicked { if(e.getSource()==quit) System.exit(0); // exit the program if the button is quit else { // otherwise set text to be the message needed for each JButton where String text=""; // the clear JButton causes the text to be empty if(e.getSource()==b1) text="Button 1 registered"; if(e.getSource()==b2) text="Button 2 registered"; if(e.getSource()==b3) text="Button 3 registered"; if(e.getSource()==clear) text=" "; lab.setText(text); // place the new text into the JLabel } } } }