GUI Program Example

// This program illustrates how to develop a simple GUI-based system.
// Program must be saved in a file named

// Import required libraries for GUI
import javax.swing.*; // GUI widgets and containers are defined here
import java.awt.event.*; // Events & the Action Listener interface are defined here

public class ExampleGUI extends JFrame // Inherit from JFrame to get basic window structure
// Define reference variables for class-wide objects; must instantiate later
private JPanel myPanel; // Basic container for GUI widgets
private JButton okButton; // GUI widgets
private JButton cancelButton;
private JTextField textField;
private JTextArea textArea;
private JLabel fieldLabel;
private JLabel areaLabel;

public ExampleGUI ( ) // Constructor does the work of setting up the GUI
final int FRAME_WIDTH =500; // Constant value for window width in pixels
final int FRAME_HEIGHT = 300; // Constant value for window height in pixels

// Instantiate all GUI containers and widgets
myPanel = new JPanel( );
okButton = new JButton (“OK”);
cancelButton = new JButton (“Cancel”);
textField = new JTextField (“Hello, World!”, 20);
textArea = new JTextArea (5,20);
fieldLabel = new JLabel (“Greeting”, SwingConstants.LEFT);
areaLabel = new JLabel (“Type some stuff here!!”, SwingConstants.CENTER);

//Set up the data for the actual window
setTitle (“My Example Graphical User Interface”);
// Default close operation is HIDE_ON_CLOSE
// Modify to allow program to better fit user expectations

// Add GUI widgets, once instantiated, to JPanel container
// Order of addition determines order of appearance

// Create event handler objects and add to buttons
okButtonHandler okListener = new okButtonHandler();
cancelButtonHandler cancelListener = new cancelButtonHandler();

// Everything is in the panel, add it to the JFrame

//The GUI is put together; make it visible
setVisible (true);

// Now wait for events to occur and handle them when they do


// Create the event handler classes for appropriate objects
// The event handlers do the actual data processing of the program

private class okButtonHandler implements ActionListener // to handle ActionEvent
public void actionPerformed (ActionEvent e) // required method for ActionListener interface implementation
//some code goes here to do whatever you want the OK button to do

private class cancelButtonHandler implements ActionListener // to handle ActionEvent
public void actionPerformed (ActionEvent e)
textField.setText(“”); // erase whatever is already in the text field & area

// The main method is very simple because the constructor does all the work.
public static void main (String [] args)
// Create the GUI object that will do everything
ExampleGUI myGUI = new ExampleGUI();