12: GUIs

What We Will Cover


Illuminations

Questions from last class?

Homework Questions?

Homework Discussion Questions

  1. How easy was it to draw simple shapes using a Graphics2D object?
  2. Did anyone use the Turtle class?

What to take next?

12.1: Graphical-User Interfaces

Learner Outcomes

At the end of the lesson the student will be able to:

  • Describe the three categories of GUI components
  • Collect user input in an input dialog box
  • Show messages using a message dialog

12.1.1: About Graphical User Interfaces (GUIs)

  • Graphical User Interface (GUI) -- pronounced "gooey"
    • Graphical: not just text or characters but includes windows, menus, buttons, etc.
    • User: person using the program via mouse, keyboard, etc.
    • Interface: interaction with the program using visual controls, widgets, etc.
  • GUIs present a user-friendly way to interact with a program
  • Most modern programs use a GUI
  • Typical graphical components include:
    • Window: portion of screen providing an area for the other components
    • Button: looks like a button that can be pressed
    • Labels: Displays text or images in the window
    • Text field: place where users can type values

Example GUI

input dialog

Java's GUI Libraries

  • GUIs are built from objects called components:
    • Also called controls or widgets
  • Users interact with GUI components using a mouse, keyboard or other input device
  • Java provides two sets of GUI components: AWT and Swing
  • AWT (Abstract Window Toolkit) is the older set of components:
    • Relies on the underlying visual components of the operating system
    • GUIs look different on every operating system
  • Swing (like the dance) is the newer set of components:
    • Extends AWT components and adds new capabilities
    • Components draw their own visual shapes on the screen
    • GUIs look about the same on every operating system
  • The inheritance hierarchy below shows how Swing extends AWT
  • Note that Swing components all start with the letter "J"
  • We will focus on how to use Swing components

Inheritance Hierarchy for GUI Components

components hierarchy

12.1.2: Component Categories

  • GUI components fall into three categories as shown below

Top-Level Containers

  • Basic window structure that ties the GUI into the operating system
  • Includes capabilities such as borders and resizability
  • Holds intermediate containers and atomic components
  • Every GUI program must have one top-level container
  • Some of the frequently used components are:
Component Description
JFrame A top-level window with a title, border and buttons for closing, maximizing/restoring and iconifying the window.
JApplet Container for applets, which are small programs that run inside a Web browser
JOptionPane Limited window that makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something.

Intermediate Containers

  • Graphical object displayed in a top-level container
  • Can also hold other intermediate containers and atomic components
  • Used to simplify placement of controls
  • Some of the frequently used components are:
Component Description
JPanel Provides a general-purpose container for atomic components and other intermediate containers.
JRootPane A container used behind the scenes by JFrame, JApplet and other containers.
JScrollPane A container that provides a scrollable view of a component.

Controls

  • Graphical objects used to accept input or display information
  • Must be placed in a container using the add method
  • Some of the frequently used components are:
Component Description
JButton Display area that triggers an event when clicked.
JComboBox Drop-down list of items from which the user can make a selection by clicking an item in the list or possibly by typing into a box.
JCheckBox GUI component that can be selected or deselected and displays its state to the user as a checked square.
JRadioButton GUI component that can be selected or deselected and displays its state to the user as a filled or unfilled circle.
JLabel Display area for text or icons
JTextField Single-line display and input area for the user to enter data from the keyboard.
JTextArea Multi-line display and input area for the user to enter data from the keyboard.

Further Information

12.1.3: Example GUI Using JOptionPane

  • One type of GUI window is known as a dialog box
  • Dialogs provide a simple "popup" type of interaction with users
  • JOptionPane provides several static methods for constructing dialogs
  • Code for dialogs can be minimal
  • For instance, to collect text input from a dialog:
    String inputString = JOptionPane.showInputDialog(
        "Enter your first name:");
    
  • Produces the following input dialog:

    input dialog

  • Most dialogs are small windows with minimal options like the above

Example Dialog Application

  • Lets create a simple program to ask for and display a name
  • We will use three types of dialog boxes in sequence:
    1. showInputDialog: ask for name
    2. showConfirmDialog: verify entry
    3. showMessageDialog: display results
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import javax.swing.JOptionPane;

public class NameApp {
    public static void main(String[] args) {
        String inputString = JOptionPane.showInputDialog(
            "Enter your first name: ");
        int choice = JOptionPane.showConfirmDialog(null,
            "Are you sure?");
        String message = "First name: " + inputString + "\n"
                         + "Choice: " + choice + "\n"
                         + "Press enter to exit.";
        JOptionPane.showMessageDialog(null, message);
        System.exit(0);
    }
}

Input with showInputDialog()

  • Use the showInputDialog method of JOptionPane to get text input from users
  • In the above example, we created the first dialog like this:
    String inputString = JOptionPane.showInputDialog(
        "Enter your first name:");
    
  • Essentially a single line of code

Input with showConfirmDialog()

  • Use the showConfirmDialog method of JOptionPane to get text input from users
  • In the above example, we created the first dialog like this:
    int choice = JOptionPane.showConfirmDialog(null,
        "Are you sure?");
    

Output with showMessageDialog()

  • Use the showMessageDialog to show the user a message
  • From the above example:
    String message = "First name: " + inputString + "\n\n"
                     + "Press enter to exit.";
    JOptionPane.showMessageDialog(null, message);
    
  • Note that you can use both showInputDialog() and showConfirmDialog() for output as well

Commonly-Used Methods of JOptionPane

Static Method Description
showConfirmDialog Asks a confirming question, like yes/no/cancel.
showInputDialog Prompts for user text input.
showMessageDialog Tell the user about something that has happened.

12.1.4: Dialog Arguments

  • Most methods of JOptionPane are overloaded to accept arguments
  • These options control dialog placement, messages and icons displayed, and title-bar wording
  • Both showInputDialog and showMessageDialog accept the arguments listed in the table below
  • showInputDialog can accept four arguments:
    JOptionPane.showInputDialog(parentComponent, messageString,
        titleString, messageTypeInt);
    
  • To display a different dialog without an input field:
    JOptionPane.showMessageDialog(parent, message);
    
  • If the parent component is unknown, you can use null for that argument
    JOptionPane.showMessageDialog(null, "Hello, world!");
    
  • You will need to look up the exact usage in the JOptionPane API documentation

Commonly-Used Arguments in JOptionPane Methods

Argument Description
parentComponent An object representing the frame of the dialog box and controls its placement on the screen. If null is used, the dialog is centered on the screen.
messageString A descriptive message displayed in the dialog box.
titleString A title typically placed in the title bar above the dialog box.
messageTypeInt Indicates the type of icon to display in the dialog box. Choosing one of the message types shown below will display the corresponding icon.
icon Used if you want to display your own icon rather than a built-in icon.

Icons provided by JOptionPane

Icon Message Type Description
metal error ERROR_MESSAGE Displays an error icon.
metal info INFORMATION_MESSAGE Displays an information icon.
metal warning WARNING_MESSAGE Displays an warning icon.
metal question QUESTION_MESSAGE Displays an question icon.
  PLAIN_MESSAGE Does not display an icon.

More Information

12.1.5: Summary

  • Graphical user interfaces (GUIs) present a user-friendly way to interact with a program
  • GUIs are built from objects called components
  • Java provides special libraries for implementing GUI interfaces, the newer of which is called Swing
  • GUI components fall into three categories:
    • Top-level containers: basic window structure that ties the GUI into the operating system
    • Intermediate containers: used to hold other components
    • Atomic components: graphical objects used to accept input or display information
  • You can create simple GUIs using JOptionPane
  • JoptionPane produces "popup" dialog boxes for simple interactions with users
  • Code for dialogs can be minimal and is usually coded using "one-liners":
    String inputString = JOptionPane.showInputDialog(
        "Enter your first name:");
    
  • Which produces the following input dialog:

    input dialog

  • Most methods of JOptionPane are overloaded to accept arguments
  • These options control dialog placement, messages and icons displayed, and title-bar wording
  • You will need to look up the exact usage in the Java API documentation

Check Yourself

  1. What are the three types of GUI components?
  2. What package(s) must be imported to create dialogs?
  3. How many statements are typically needed to code a dialog box?

Exercise 12.1

Take one minute to prepare answers to the above questions.

12.2: Building a Simple GUI Application

Learner Outcomes

At the end of the lesson the student will be able to:

  • Work with frames
  • Add a panel to a frame
  • Add buttons to a panel
  • Handle button events

12.2.1: Working With JFrames

  • A JFrame is a top-level component commonly used with Java applications
  • It inherits many methods from both the Frame and Window class
  • By default, all JFrames start with a size of 0 x 0 pixels and open in the top left corner of the screen
  • To code a GUI application, you can extend a JFrame:
    public class HelloWindow extends JFrame
    
  • To close a JFrame, you often use the method setDefaultCloseOperation():
    setDefaultCloseOperation(EXIT_ON_CLOSE);

Example JFrame

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import javax.swing.*;

public class HelloFrame extends JFrame {
    public static final int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;

    public HelloFrame() {
        super("Hello Frame Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new HelloFrame();
    }
}

Commonly Used Methods of the Frame Class

Method Description
setTitle(StringObj) Sets the title bar to the specified string.
setResizable(booleanValue) Sets whether or not this frame can be resized.

Commonly Used Methods of the Window Class

Method Description
hide() Hides this window without closing it.
pack() Size this window to fit the preferred size and layout of its components.
show() Makes this window visible.

Commonly Used Methods of the Component Class

Method Description
getHeight() Returns the height of the component as an int.
getWidth() Returns the width of the component as an int.
getX() Returns the x coordinate of the components as an int.
getY() Returns the y coordinate of the components as an int.
setLocation(intX, intY) Moves this component to a new (x, y) location.
setSize(intWidth, intHeight) Resizes this component to a new width and height.
setBounds(intX, intY, intWidth, intHeight) Moves and resizes this component.
setVisible(booleanValue) Shows or hides this component depending on the value of the argument.

12.2.2: Adding a Panel to a Frame

  • After you create a frame, you need to add components to it
  • One component you often add is a JPanel
  • The JPanel is an general-purpose container
  • You use a JPanel to enclose other components
  • The code to add a JPanel to the content pane of a JFrame is:
    JPanel panel = new JPanel();
    Container contentPane = getContentPane();
    contentPane.add(panel);
    
  • The content pane is a Container class that stores all the non-menu components for a JFrame
  • However, since Java 5, you can add components to a JFrame using the add() method of the JFrame
  • This simplifies the code for adding components to:
    JPanel panel = new JPanel();
    add(panel);
    
  • You can add components, such as buttons, directly to the content pane
  • However, you often add components to a panel and then add the panel to the content pane
  • This helps you to group components so your code is easier to read and understand

Methods to Add Components to the Content Pane

Method Description
getContentPane() Returns the content pane as a Container object.
add(componentObj) Adds a component object to this container.

12.2.3: Adding Buttons to a Panel

  • Button: a component the user clicks to trigger a specific action
  • Basic buttons are created with class JButton
  • You can add a button to a panel like this:
    JPanel panel = new JPanel();
    JButton button = new JButton("Hello");
    panel.add(button);
    
  • The first two statements create the panel and the button
  • The third statement adds the button to the panel
  • The following example adds two buttons to a panel and then adds the panel to a frame

Example Application with Button Components

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.awt.*;
import javax.swing.*;

public class HelloFrame2 extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    private JButton helloButton;
    private JButton exitButton;

    public HelloFrame2() {
        super("Hello Frame Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        helloButton = new JButton("Hello");
        exitButton = new JButton("Exit");
        JPanel panel = new JPanel();
        panel.add(helloButton);
        panel.add(exitButton);
        add(panel);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new HelloFrame2();
    }
}

Commonly Used Constructors of the JButton Class

Constructor Description
JButton() Creates a button without any text or icons.
JButton(StringObj) Creates a button displaying the specified text.
JButton(IconObj) Creates a button displaying the specified icon.
JButton(StringObj, IconObj) Creates a button displaying both the specified string and icon.

Some Methods of the JButton Class

Method Description
getText() Returns the text of this button as a String.
setText(StringObj) Sets the text of this button.
setEnabled(booleanValue) Enables the button if the argument is true; otherwise it disables the button.

12.2.4: Handling Button Events

  • So far the buttons do not respond when the user clicks them
  • To make them respond, you need to add code that is executed when a button is clicked
  • This is known as event-handling code
  • The following only shows how to handle button events
  • However, you use the same principles to handle other types of events

How To Handle Action Events

  1. Specify that a class implements the ActionListener interface:
    public class HelloFrame3 extends JFrame
            implements ActionListener {
    
  2. Register the ActionListener object with the button by calling the addActionListener() method:
    helloButton.addActionListener(this);
    
  3. Implement the ActionListener interface by coding an actionPerformed() method:
    public void actionPerformed(ActionEvent ae) {
        Object source = ae.getSource();
        if (source == helloButton) {
            JOptionPane.showMessageDialog(this, "Hello");
        } else if (source == exitButton) {
            System.out.println("Goodbye!");
            System.exit(0);
        } else {
            System.out.println("Unknown ActionEvent");
        }
    }
    

Identifying the Component Firing the Event

  • Note that the getSource() method of an event object returns the memory location of the object that generated the event.
  • This allows you to compare the value returned by getSource() against references to components:
    Object source = ae.getSource();
    if (source == helloButton) {
        // now you know the helloButton was pressed
    }
    
  • The above code allows you to identify the component that fired the event

Example Application with an Event Handler

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloFrame3 extends JFrame
        implements ActionListener {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    private JButton helloButton;
    private JButton exitButton;

    public HelloFrame3() {
        super("Hello Frame Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        helloButton = new JButton("Hello");
        helloButton.addActionListener(this);
        exitButton = new JButton("Exit");
        exitButton.addActionListener(this);
        JPanel panel = new JPanel();
        panel.add(helloButton);
        panel.add(exitButton);
        add(panel);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent ae) {
        Object source = ae.getSource();
        if (source == helloButton) {
            JOptionPane.showMessageDialog(this, "Hey");
        } else if (source == exitButton) {
            System.out.println("Goodbye!");
            System.exit(0);
        } else {
            System.out.println("Unknown ActionEvent");
        }
    }

    public static void main(String[] args) {
        new HelloFrame3();
    }
}

12.2.5: Using Other Components

  • In this section we will look at how to use some more Swing components
    • JLabels
    • JTextFields
  • These components are the most commonly used and may be all you need for games
  • Also, many other components work like these if you decide to branch out

JLabels

  • A JLabel is typically used to display text on a panel
  • For instance, you may want a label for a text field
  • The following code adds a label to a panel:
    JPanel panel = new JPanel();
    JLabel label = new JLabel("Label text");
    panel.add(label);
    
  • Other constructors of a JLabel allow Icons as well

Commonly-Used Constructors and Methods from JLabel

Constructor/Method Description
JLabel() Creates a blank label.
JLabel(Icon) Creates a label with the specified image.
JLabel(String) Creates a label with the specified text.
setIcon(Icon) Sets the icon for a label.
setText(String) Sets the text for a label.

JTextField

  • JTextField: single-line area in which user can enter text
  • The following code adds a text field to a panel with space for 10 characters:
    JPanel panel = new JPanel();
    JTextField text = new JTextField(10);
    panel.add(text);
    

Commonly-Used Constructors and Methods from JTextField

Constructor/Method Description
JTextField(int) Creates an empty text field with the specified number of columns.
JTextField(String, int) Creates a text field that starts with the text and contains the number of columns.
getText() Returns the text contained in the text field as a String object.
setText() Sets the text field to the specified String.
setColumns(int) Sets the number of columns for the text field.

Example with Various Components

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.awt.event.*;
import javax.swing.*;

public class MultiComp extends JFrame
        implements ActionListener {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    private JTextField nameField;
    private JButton okButton;
    private JButton cancelButton;

    private static final String INSTRUCTIONS =
        "<html>Enter your name and press the OK button."
        + "<br>To skip this step, press the Cancel button";

    public MultiComp() {
        super("Multiple Components");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Create components
        JLabel instructions = new JLabel(INSTRUCTIONS);
        nameField = new JTextField(10);
        okButton = new JButton("OK");
        cancelButton = new JButton("Cancel");

        // Create JPanel and add components to the panel
        JPanel panel = new JPanel();
        panel.add(instructions);
        panel.add(nameField);
        panel.add(okButton);
        panel.add(cancelButton);
        add(panel);

        // Add action listeners
        nameField.addActionListener(this);
        okButton.addActionListener(this);
        cancelButton.addActionListener(this);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent ae) {
        Object source = ae.getSource();
        if (source == okButton || source == nameField) {
            JOptionPane.showMessageDialog(this,
                "Hey, " + nameField.getText() + "!");
        } else if (source == cancelButton) {
            System.out.println("Action canceled");
            System.exit(0);
        } else {
            System.out.println("Unknown ActionEvent");
        }
    }

    public static void main(String[] args) {
        new MultiComp();
    }
}

12.2.6: Summary

  • Most Java GUI applications inherit from a JFrame:
    public class HelloWindow extends JFrame
  • To close a JFrame, you often use the method setDefaultCloseOperation():
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  • To add components to a JFrame, you often use a JPanel as an intermediate container
  • To add button components, you use the JButton class
  • The code for adding buttons is something like:
    JPanel panel = new JPanel();
    helloButton = new JButton("Hello");
    panel.add(helloButton);
    add(panel);
    
  • To make a button respond when clicked, you add an ActionEvent handler
  • There are three steps for adding an ActionEvent handler:
  1. Specify that a class implements the ActionListener interface:
    public class HelloFrame3 extends JFrame
            implements ActionListener {
    
  2. Register the ActionListener object with the button by calling the addActionListener() method:
    helloButton.addActionListener(this);
    
  3. Implement the ActionListener interface by coding the actionPerformed() method:
    public void actionPerformed(ActionEvent ae) {
        // event handling code
    }
    
  • You handle other events using code like that used for the ActionEvent

Check Yourself

  1. How does a component, like a JButton, signal that it was used?
  2. How does an object become a listener?
  3. How does an event get passed to a listener object?
  4. What code is executed when an event occurs?

Exercise 12.2

Take one minute to prepare answers to the above questions.

12.3: Laying Out Components

Learner Outcomes

At the end of the lesson the student will be able to:

  • Describe the purpose of a layout manager
  • Use the Flow layout Manager
  • Use the Border layout Manager
  • Describe how to organize layout code

12.3.1: About Layout Managers

  • When you add multiple components to a GUI, your program has to set the size and position of each component.
  • You use a layout manager to provide this functionality
  • Each Container object has a default layout manager
  • For instance, a JPanel uses a FlowLayout manager
  • On the other hand, content panes like those used in JFrame use a BorderLayout manager
  • Normally, you only need to think about layout managers when:
    1. You add components to a container
    2. You do not like the default layout manager
  • To change the layout manager, you use the setLayout() method of the container
  • We will discuss two commonly used layout managers in the next few sections

Method of the Container Class Used to Change Layout Managers

Method Description
setLayout(LayoutManagerObj) Sets the layout manager for this container.

12.3.2: Using the FlowLayout Manager

  • The FlowLayout manager is the default for a JPanel
  • It adds components to the top of a container moving from left to right
  • When a container runs out of horizontal space, it starts adding components to a new row
  • You can adjust the alignment of the components on a row using the alignment fields of the FlowLayout class:
    • FlowLayout.CENTER
    • FlowLayout.LEFT
    • FlowLayout.RIGHT
  • Unlike some layout managers, the FlowLayout respects component sizes

Example Using a FlowLayout Manager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.awt.*;
import javax.swing.*;

public class FlowLayoutApp extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JButton button5;

    public FlowLayoutApp() {
        super("Flow Layout Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        button1 = new JButton("Button One");
        button2 = new JButton("Button Two");
        button3 = new JButton("Button with a long name");
        button4 = new JButton("Button Four");
        button5 = new JButton("5");

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.LEFT));
        panel.add(button1);
        panel.add(button2);
        panel.add(button3);
        panel.add(button4);
        panel.add(button5);
        add(panel);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new FlowLayoutApp();
    }
}

Commonly Used Constructors of the FlowLayout Class

Constructor Description
FlowLayout() Constructs a new FlowLayout with a centered alignment.
FlowLayout(intAlign) Constructs a new FlowLayout with the specified alignment.

More Information

12.3.3: Using the BorderLayout Manager

  • You can align buttons left or right with a FlowLayout manager
  • However, you cannot place buttons at the bottom of the container
  • To do that, you can use the BorderLayout manager
  • With a BorderLayout manager, you can place components in 5 separate regions:

    borderlayout

  • Each region can hold only a single component

Adding and Using a BorderLayout Manager

  • To create a new BorderLayout, you typically call its no-parameter constructor:
    BorderLayout bl = new BorderLayout()
    
  • To add the BorderLayout to a container you use the setLayout() method:
    panel.setLayout(new BorderLayout());
    
  • The default layout manager of a content pane is BorderLayout
  • To add a component to a container using a BorderLayout, you specify:
    add(ComponentObj, regionField);
  • If you do not specify the region, the component is added to the center region
  • Note that BorderLayout ignores the preferred sizes of components
  • Thus, a component will adjust itself to fit the size of the region in which it is placed

Example Using a BorderLayout Manager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.awt.*;
import javax.swing.*;

public class BorderLayoutApp extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    private JButton buttonNorth;
    private JButton buttonSouth;
    private JButton buttonEast;
    private JButton buttonWest;
    private JButton buttonCenter;

    public BorderLayoutApp() {
        super("BorderLayout Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        buttonNorth = new JButton("North");
        buttonSouth = new JButton("South");
        buttonEast = new JButton("East");
        buttonWest = new JButton("West");
        buttonCenter = new JButton("Center");

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(buttonNorth, BorderLayout.NORTH);
        panel.add(buttonSouth, BorderLayout.SOUTH);
        panel.add(buttonEast, BorderLayout.EAST);
        panel.add(buttonWest, BorderLayout.WEST);
        panel.add(buttonCenter, BorderLayout.CENTER);
        add(panel);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new BorderLayoutApp();
    }
}

Commonly Used Constructors of the BorderLayout Class

Constructor Description
BorderLayout() Constructs a new BorderLayout.

More Information

12.3.4: Combining Layout Managers

  • The FlowLayout manager lets you align components left, center or right
  • However, it does not let you place components at the bottom of the container
  • On the other hand, the BorderLayout manager lets you put components at the bottom
  • But, you can only place one component in the bottom region
  • To get multiple components at the bottom of a window, you must combine layout managers

    combinded layout

  • Since you can only have one layout manager per container, you must have multiple containers to get the effect of multiple layouts
  • The following code shows how you add two layouts together
  • The first container is named panel and uses a BorderLayout:
    buttonNorth = new JButton("North");
    buttonEast = new JButton("East");
    buttonWest = new JButton("West");
    buttonCenter = new JButton("Center");
    
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    panel.add(buttonNorth, BorderLayout.NORTH);
    panel.add(buttonEast, BorderLayout.EAST);
    panel.add(buttonWest, BorderLayout.WEST);
    panel.add(buttonCenter, BorderLayout.CENTER);
    
  • The second container is named flowPanel and uses a FlowLayout:
    label = new JLabel("Label text", JLabel.LEFT);
    button = new JButton("Button text");
    JPanel flowPanel = new JPanel();
    flowPanel.setLayout(
        new FlowLayout(FlowLayout.RIGHT));
    flowPanel.add(label);
    flowPanel.add(button);
    
  • We then add the secondPanel to the firstPanel:
    panel.add(flowPanel, BorderLayout.SOUTH);
    
  • Thus you combine layouts by nesting one container inside another container
  • The complete code is shown below

Example Using a Combination of Layout Managers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.awt.*;
import javax.swing.*;

public class CombinedLayoutApp extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 150;
    private JButton buttonNorth;
    private JButton buttonEast;
    private JButton buttonWest;
    private JButton buttonCenter;
    private JButton button;
    private JLabel label;

    public CombinedLayoutApp() {
        super("Combined Layout Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        buttonNorth = new JButton("North");
        buttonEast = new JButton("East");
        buttonWest = new JButton("West");
        buttonCenter = new JButton("Center");

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(buttonNorth, BorderLayout.NORTH);
        panel.add(buttonEast, BorderLayout.EAST);
        panel.add(buttonWest, BorderLayout.WEST);
        panel.add(buttonCenter, BorderLayout.CENTER);

        label = new JLabel("Label text", JLabel.LEFT);
        button = new JButton("Button text");
        JPanel flowPanel = new JPanel();
        flowPanel.setLayout(
            new FlowLayout(FlowLayout.RIGHT));
        flowPanel.add(label);
        flowPanel.add(button);

        panel.add(flowPanel, BorderLayout.SOUTH);
        add(panel);

        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new CombinedLayoutApp();
    }
}

12.3.5: Other Layout Managers

Java provides other layout managers you can research and use including:

  • BoxLayout: positions components in a single row or column
  • CardLayout: lets you create an area that can contain different components at different times
  • GridBagLayout: places components in a grid and allows some components to span more than one cell
  • GridLayout: displays components with equal size in a row-column layout like a spreadsheet
  • GroupLayout: displays components with horizontal and vertical layouts defined separately
  • SpringLayout: allows you to specify precise relationships between the edges of components

More Information

12.3.6: Absolute Positioning

  • It is possible to do without a layout manager and use absolute positioning
  • However, you should use a layout manager if at all possible
  • Not using a layout manager creates a rigid and inflexible user interface
  • If you allow the user to resize a frame, then components can get hidden
  • To show the components optimally, you can make the frame a fixed size and not resizeable
  • However, a fixed-size frame can interfere with other applications the user is running
  • To get a feel for these limitations, run the following example

Example of Absolute Positioning

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.awt.*;
import javax.swing.*;

public class AbsoluteApp extends JFrame {
    public final static int X_LOC = 100, Y_LOC = 100,
                            WIDTH = 300, HEIGHT = 170;
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    private JButton button5;

    public AbsoluteApp() {
        super("Absolute Positioning Application");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        button1 = new JButton("Button One");
        button2 = new JButton("Button Two");
        button3 = new JButton("Button with a long name");
        button4 = new JButton("Button Four");
        button5 = new JButton("5");

        button1.setBounds(10, 10, 100, 50);
        button2.setBounds(120, 10, 100, 50);
        button3.setBounds(230, 10, 150, 50);
        button4.setBounds(10, 70, 100, 50);
        button5.setBounds(120, 70, 50, 50);

        JPanel panel = new JPanel();
        panel.setLayout(null);
        panel.add(button1);
        panel.add(button2);
        panel.add(button3);
        panel.add(button4);
        panel.add(button5);

        add(panel);
        setBounds(X_LOC, Y_LOC, WIDTH, HEIGHT);
        setVisible(true);
    }

    public static void main(String[] args) {
        new AbsoluteApp();
    }
}
  • To remove the layout manager, you set the layout to null:
    panel.setLayout(null);
    
  • Now you need to set the position and size of each component individually:
    button1.setBounds(10, 10, 100, 50);
    

More Information

12.3.7: Summary

  • When you add multiple components to a GUI, your program has to set the size and position of each component
  • You use a layout manager to provide this functionality
  • Normally, you only need to think about layout managers when:
    • You add components to a container
    • You do not like the default layout manager
  • To set a new layout for a container, you use the setLayout() method
  • To set a new FlowLayout for a panel, you code something like:
    panel.setLayout(new FlowLayout(FlowLayout.LEFT));
    
  • To set a new BorderLayout for a panel, you code something like:
    panel.setLayout(new BorderLayout());
    
  • To add a component to a container using a BorderLayout, you code something like:
    panel.add(button1, BorderLayout.NORTH);
    
  • If you do not specify the region, the component is added to the center region
  • You can combine layout managers using multiple containers
    • One container is added to another container
    firstPanel.add(secondPanel, BorderLayout.SOUTH);
    
  • Java has other layout managers you can use:
  • Also, you can remove the layout manager and set all the component positions and sizes individually
  • However, you produce more professional and user friendly applications by using a layout manager

Exercise 12.3

Take one minute to prepare answers to the following questions:

  1. How are components positioned with a BorderLayout manager?
  2. How are components positioned with a FlowLayout manager?

Wrap Up

Due Next:
A10-Graphics and Recursion (5/5/10)
Course Project (5/26/10)
Work on your project!
Home | Blackboard | Schedule | Room Policies | Syllabus
Help | FAQ's | HowTo's | Links
Last Updated: May 05 2010 @12:33:58