import javax.swing.*; import java.awt.*; //this does NOT include java.awt.event classes import java.awt.event.*; public class SimpleGui { //these objects are declared at the class level //if we declared them inside any one of the methods, the various OTHER methods //would not be able to see them (an issue of SCOPE) JFrame frame; JButton simpleB, exitB; /* - The bulk of this program's code is NOT inside main, instead, we use main() only to instantiate the current class, and then use that instantiation to invoke a method that DOES contain the bulk of the code - This has to do with static/non-static issues. */ public static void main(String[] args) { SimpleGui g = new SimpleGui(); g.go(); } //end method main() /* This method contains the bulk of our program's code. See the comment preceding 'main()' */ public void go() { frame = new JFrame("Practice GUI"); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); simpleB = new JButton("Click Me"); exitB = new JButton("Exit"); //The first argument to the add() method will make more sense when we discuss layouts frame.add(BorderLayout.CENTER, simpleB); frame.add(BorderLayout.SOUTH, exitB); //Tell the button that this class is a 'listener' //This is known as "registering" as a listener //ANY class can be registered as a listener simpleB.addActionListener( new SimpleButtonHandler() ); exitB.addActionListener( new ExitButtonHandler() ); frame.setVisible(true); } //end method go() /*//////////////////////////////////////////// private class... --> this class within a class is allowed in Java. It is known as an 'inner' or 'nested' class --> note the private visiblity; there is no need for it to be public "...implements ActionListener": - Implementing ActionListener interface - Allows us to include the actionPerformed method below *** When this class is registered with an event-generator such as a button with the command: button.addActionListener( new ButtonHandler() ); the actionPerformed method will be called whenever the button is clicked - Some of this will be explained in more detail when we cover interfaces. */ private class SimpleButtonHandler implements ActionListener { //In order to implement the ActionListener interface, the body for the actionPerformed //method must be provided. public void actionPerformed(ActionEvent ae) { System.out.println("The Try Me! button was clicked!"); } //end method actionPerformed() } //end SimpleButtonHandler private class ExitButtonHandler implements ActionListener { public void actionPerformed(ActionEvent ae) { System.exit(0); } //end method actionPerformed() } //end ExitButtonHandler } //end class SimpleGui