// SwingGUIsFrameDemoOneInnerClass.java // One JButton widget in a JFrame. similar to SwingGUIsFrameDemoOne.java //**but ActionListener is an anonymous inner class (instead of "this" ). // anonymous: has no name. compiler creates name of class file with $1. // inner class: a class defined inside another class. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SwingGUIsFrameDemoOneInnerClass { //** does NOT implement ActionListener private JFrame outputFrame; private Container container; private JButton myButton; public static void main( String [] args ) { SwingGUIsFrameDemoOneInnerClass myFrameDemo = new SwingGUIsFrameDemoOneInnerClass(); } //constructor public SwingGUIsFrameDemoOneInnerClass() { outputFrame = new JFrame(); outputFrame.setSize(600,500); outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); container = outputFrame.getContentPane(); container.setLayout( new FlowLayout() ); myButton = new JButton( "My JButton" ); container.add( myButton ); //**handler is actionPerformed method of object of anonymous inner class //that implements ActionListener interface is defined and instantiated //in the parameter of addActionListener method. myButton.addActionListener( //method call new ActionListener() { //instantiate object public void actionPerformed( ActionEvent event ) { JOptionPane.showMessageDialog(null,"myButton got it"); } } ); //end of addActionListener method call //** useful for having action listener per widget: //myWidget.addActionListener(new ActionListener(){...}); //it's a common way to do the event handling. //it's a common use of anonymous inner classes. outputFrame.setVisible(true); } }