Home CPSC 220

GUI Programming

 

Overview

Today we will look at creating GUI programs with Java. GUI programming in Java involves creating and using multiple objects of different classes. The flow of GUI programs is also quite different.


 

Swing Hello World

The GUI library that comes with Java is called Swing. Below is a hello world program in Swing:


import javax.swing.*;

public class HelloWorld {
    public static void main(String args[]) {
        // create and set up the window.
        JFrame frame = new JFrame("Hello World!");

        // make the program close when the window closes
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // add a "Hello World" label.
        JLabel label = new JLabel("Hello World");
        frame.getContentPane().add(label);

        // display the window.
        frame.pack();
        frame.setVisible(true);
    }    
}

The JFrame class represents a window. Each GUI program we will write contains a JFrame object. This program also contains a JLabel object which just displays some text.


 

Buttons

The following example demonstrates a button added to the window instead of a label:


import javax.swing.*;

public class Buttons {
    public static void main(String args[]) {
        // create and set up the window.
        JFrame frame = new JFrame("Button Example!");

        // make the program close when the window closes
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // add a button object
        JButton button = new JButton("Push Me!");
        frame.getContentPane().add(button);

        // display the window.
        frame.pack();
        frame.setVisible(true);
    }    
}

Now we add a JButton object to the screen instead of a JLabel.

Unfortunately clicking the button does nothing.


 

Events

GUI programs work much differently from console programs. In a GUI program, the control of execution is not linear. Instead, the program responds to the users actions via events.

To make our button take some action when it is pressed, we need to use events.

This example shows adding an event handler for the button:


import javax.swing.*;
import java.awt.event.*;

class ButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, "You pushed the button!!");
    }
}

public class Buttons2 {
    public static void main(String args[]) {
        // create and set up the window.
        JFrame frame = new JFrame("Button Example!");

        // make the program close when the window closes
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // add a button object
        JButton button = new JButton("Push Me!");
        button.addActionListener(new ButtonListener());
        frame.getContentPane().add(button);

        // display the window.
        frame.pack();
        frame.setVisible(true);
    }    
}

Here, the actionPerformed method is called automatically when the button is pressed. The only type of objects that can respond to button presses are ActionListener objects. In order to create one, we then need to implement the ActionListener interface, and override the actionPerformed function.

This also demonstrates creating a message box.


 

Menus

This example shows shows using a menu bar:


import java.awt.event.*;
import javax.swing.*;

// this class contains the method called when the exit choice is picked
class ExitListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.exit(0);
    }
}

public class test {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Menu Example!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // create the menu bar
        JMenuBar menubar = new JMenuBar();

        // add the file menu
        JMenu file = new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);

        // add a menu item
        JMenuItem exit = new JMenuItem("Exit", null);
        exit.setMnemonic(KeyEvent.VK_E);
        exit.setToolTipText("Exit the program");

        // add the action as a new anonymous object
        exit.addActionListener(new ExitListener());
        file.add(exit);

        // add file to the menubar
        menubar.add(file);

        // add the menubar to the window
        frame.setJMenuBar(menubar);

        // set other things
        frame.setTitle("Simple menu");
        frame.setSize(300, 200);

        // launch the windwo
        frame.setVisible(true);
    }
}

The JMenuBar class represents the whole menu bar. The JMenu class represents one individual menu, such as "File" or "Edit" in typical programs. The JMenuItem class represents one specific entry such as "Exit", or "Copy".


 

Layouts

Typically GUI programs will use more than one GUI component at a time. When doing this, we'll need to specify how they appear together. This is done with layouts in Swing.

The simplest layout is the BoxLayout which specifies that elements in it appear in a vertical or horizotal list.

The following example demonstrates the box layout.


import javax.swing.*;
import java.awt.event.*;


class ButtonListener implements ActionListener {
    // each button listener stores the name of the button
    private String text;
    
    // given the text when it's created 
    public ButtonListener(String t) {
        text = t;
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null, "You pushed button " + text);
    }
}

public class test {
    public static void addButton(String text, JFrame f) {
        // add a button object
        JButton button = new JButton(text);
        button.addActionListener(new ButtonListener(text));
        f.getContentPane().add(button);
    }

    public static void main(String args[]) {
        // create and set up the window.
        JFrame frame = new JFrame("Button Example!");

        // make the program close when the window closes
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // create the box layout
        frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));

        // add some buttons
        addButton("A", frame);
        addButton("B", frame);
        addButton("C", frame);
        addButton("D", frame);

        // display the window.
        frame.pack();
        frame.setVisible(true);
    }    
}

Copyright © 2024 Ian Finlayson | Licensed under a Creative Commons BY-NC-SA 4.0 License.