import java.awt.*; // older GUI library, has layout stuff for components import java.awt.event.*; // events import javax.swing.*; // swing is a library of GUI components // example of buttons with actionlisteners // class extends JFrame, so it is its own window // class is an ActionListener - will provide a method to respond to an event public class Outer extends JFrame implements ActionListener{ // keep count of how many times each button was clicked private int times1; private int times2; private int times3; private JButton button1; private JButton button2; private JButton button3; // constructor does all setup of window and buttons public Outer() { // call the JFrame constructor super("I have a button"); times1 = 0; times2 = 0; times3 = 0; // using methods inherited from JFrame // close the program if we close the window setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // width, height in pixels -- better to use pack() // setSize(400, 80); // put new added widgets in from left to right setLayout(new FlowLayout()); // button using an inner class as actionlistener button1 = new JButton("Button 1 - " + times1); button1.addActionListener(new Inner()); // button using an anonymous inner class as actionlistener button2 = new JButton("Button 2 - " + times2); button2.addActionListener( // the anonymous inner class to respond to clicks from button 2 // since it it inner class, it can access times2 and button2 new ActionListener() { // implementing this interface public void actionPerformed(ActionEvent e) { times2 ++; button2.setText("Button 2 - " + times2); } } ); // button using the class it is in as actionlistener button3 = new JButton("Button 1 or 3 - " + times3); button3.addActionListener(this); // also use this actionlistener if button 1 is pushed // button 1 has two actionlisteners triggered with every click button1.addActionListener(this); // put the buttons in the window add(button1); add(button2); add(button3); // size based on widgets pack(); // make the window visible setVisible(true); } // class to respond to clicks from button 1 // since it is inner class, it can access times1 and button1 private class Inner implements ActionListener { public void actionPerformed(ActionEvent e) { times1 ++; button1.setText("Button 1 - " + times1); } } // outer can be an actionlistener too // respond to clicks from button 1 or 3 public void actionPerformed(ActionEvent e) { times3 ++; button3.setText("Button 1 or 3 - " + times3); } // main to launch the GUI public static void main(String[] args) { // two separate windows, with their own variables // and own inner classes separate from each other Outer outerEx1 = new Outer(); Outer outerEx2 = new Outer(); } }