Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material...

36
Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permi

Transcript of Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material...

Page 1: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Introduction to Java GUICreating Graphical User Interfaces

© copyright Bobby Hoggard / material may not be redistributed without permission

Page 2: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Import Packages for GUI

java.awt.*

AWT (abstract window toolkit) is the main Java package usedto create and display GUI objects

AWT heavily relies on the native operating system to create and display the graphical objects

As a result, your GUI interfaces will not look the same on every system

“heavyweight” components

Page 3: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Import Packages for GUI

javax.swing.*

Swing is a package of GUI objects which is more-or-less pure Java

Swing uses AWT to create a window, and then paints pictures of GUI objects inside the window, instead of relying on the operating system to do this

As a result, your GUI interfaces should look about the same on every system

Swing allows for a pluggable look and feel to easily change the style

“lightweight” components (mostly)

Page 4: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Containers

GUI objects are grouped together inside some type of

container object

To create a graphical user interface for a Java program, you must:• Create a container object

• Add GUI components to the container object

• Add code which will execute in response to the object events

This concept is no different from any other data structure that you would have previously used

Page 5: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Containers are Data Structures

Linked ListsLinkedList list = new LinkedList();

list.add(data1);

list.add(data2);

ContainersContainer container = new Container();

container.add(obj1);

container.add(obj2);

data1 data1

head

list

obj1 obj2

head

container

Page 6: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Top-Level Containers

Top-level containers are the main containers for a Java program

A Java GUI program begins by creating a top-level container, and

then adds GUI components to it

Top-level containers can appear on their own on the screen – all other types of containers must go inside a top-level container

Page 7: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Container Hierarchy

All top-level containers classes are children of the Container class, which is derived from the Component class of the java.awt package

The main window for a desktop application is a JFrame whereas the main container for a browser applet is JApplet

Component

Container

Panel

Applet

JApplet

Window

JWindow

JDialog

JFrame

Page 8: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Types of Windows

JFrame: Contains a title bar, menu bars, and a border. Can be minimized/maximized/closed.

JDialog: Used to create dialog boxes.Often used to obtain more detailed user input or show more detailed output.

JWindow: Has no trimmings.Often used for pop-up windows and splash screens.

Page 9: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Container Layers

Root Pane: Manages/contains all of the layers.

Layered Pane: Serves to position its contents in regards to depth (called Z order). Allows overlapping components to appear on top of each other. Holds content and menu.

Menu Bar: The home for the root container’s menus

Content Pane: Container for the root pane’s visible components (excluding the menu bar).

Glass Pane: Acts like a sheet of glass over all other layers. It is completely transparent unless you paint something on it.

Soups Salads Entrees Desserts

Order Here

Root Pane

Layered Pane

Content Pane

Glass Pane

Menu Bar

Students

10% off

Page 10: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Hello World Example

package example01;import javax.swing.*;

public class HelloWorld {

public static void main(String[] args) {

JFrame frame = new JFrame("Hello World");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JLabel label = new JLabel("Hello World");

frame.getContentPane().add(label);

frame.pack();

frame.setVisible(true); }}

Memoryframe

label

Page 11: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Make It Betterpackage example01;import javax.swing.*;

public class HelloWorld {

public static void main(String[] args) { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); }}

package example01;import javax.swing.*;

public class HelloWorld {

public static JFrame createGUI() { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); }

public static void main(String[] args) { JFrame mainframe = createGUI(); mainframe.setVisible(true); }}

Page 12: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Threads

Threads are units of execution in a program

Java programs start with one thread, which begins by executingthe code in the main program

Programs can create additional threads which are all operating simultaneously

Programs which contain more than one thread are multithreaded programs

Java GUI programs are multithreaded

Page 13: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Threads in Swing Programs

There are three major types of threads used in swing programs:

• Initial threadsexecute initial application code

• The event dispatch threadhandles all of the events for the GUI

• Worker threadsexecutes time-consuming background tasks so that the user interface does not freeze while the task is being performed

Page 14: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

The Event Dispatch Thread

Executes code which handles GUI events (button presses, mouse movement, etc.)

Most Swing object methods are not thread safe – invoking them from multiple threads risks consistency errors in memory that are hard to debug

As a result, all GUI updating should be handled by this thread

Jobs to be executed by this thread must be scheduled with theinvokeLater or invokeAndWait methodsof the javax.swing.SwingUtilities class

Page 15: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Initial Threads

In standard Java applications, one initial thread starts the main method(for applets, the initial threads construct the applet and invoke its init and start methods)

For Swing programs, the initial threads do not have much to do

The main task is to initialize the GUI and schedule itto be executed by the event dispatch thread

Page 16: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Worker Threads

Tasks can be performed by the event dispatch threadas long as they complete quickly

If tasks executed by the event dispatch thread take too long, then the GUI becomes unresponsive to the user’s input

To prevent this, worker threads are used fortime consuming tasks, leaving the EDTto take care of the GUI events

Page 17: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

So What Does Main Do?

invokeLaterThis method needs an Runnable object as a parameter

Runnable objects contain a run method which is executed when the object is used to create a thread

Anonymous class: a class which is declared and instantiated at the same time. Used when the class is only needed once.

new Runnable() { public void run() { mainFrame.setVisible(true); }}

Initialize the GUI

Jframe mainframe = createGUI();

Schedule it to be executed by the event dispatch thread

SwingUtilities.invokeLater();

Schedule it to be executed by the event dispatch thread

Page 18: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Hello World Better

package example01;import javax.swing.*;

public class HelloWorld {

public static JFrame createGUI() { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); }

public static void main(String[] args) { JFrame mainframe = createGUI();

SwingUtilities.invokeLater(new Runnable() { public void run() { mainframe.setVisible(true); } }); }}

MainThread

Create GUI

Schedule for theEDT to make itvisible

E D T

HandleGUI events

setVisible

Page 19: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Make it Even Better!

public class HelloWorld { public static JFrame createGUI() { JFrame frame = new JFrame("Hello World");

Instead of having the main program class

“create” a JFrame…

public class HelloWorld extends JFrame {Let the main program class

actually “BE” a JFrame

public class HelloWorld extends JFrame { private JLabel label;

Objects in the frame should then be class variables so they are accessible from

any method

Page 20: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

package example01;import javax.swing.*;

public class HelloWorld {

public static JFrame createGUI() { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); }

public static void main(String[] args) { JFrame mainframe = createGUI();

SwingUtilities.invokeLater(new Runnable() { public void run() { mainframe.setVisible(true); } }); }}

package example01;import javax.swing.*;

public class HelloWorldEvenBetter extends JFrame {

private JLabel label;

public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); }

private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); }}

Hello World Even Better

Page 21: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Where Did Main Go?

We have two options:

Option #1

Since this class is now a JFrame, main can be moved into a separate class

In this new main class, instead ofcreating a “JFrame” object, you will need to create a “HelloWorldEvenBetter” object

package example01;import javax.swing.*;

public class HelloWorldEvenBetter extends JFrame {

private JLabel label;

public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); }

private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); }}

Page 22: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Option #1

HelloWorldEvenBetter.javapackage example01;import javax.swing.*;

public class HelloWorldEvenBetter extends JFrame {

private JLabel label;

public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); }

private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); }}

MainApplication.javapackage example01;import javax.swing.*;

public class MainApplication {

public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new HelloWorldEvenBetter().setVisible(true); } }); }}

Page 23: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Option #2

Any Java class can contain a main method – meaning that any class can be made to be “executable”

It is preferred to do this, for the main GUI frame

package example01;import javax.swing.*;

public class HelloWorldEvenBetter extends JFrame {

private JLabel label;

public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); }

private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); }

public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new HelloWorldEvenBetter().setVisible(true); } }); }}

HelloWorldEvenBetter.java

Page 24: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

One More Revision

The invokeLater method wants a Runnable object as a parameter

We created an anonymous class with only a single (required) run method

When you create an anonymous class in this manner, it can be replaced with a lambda expression instead

Lambda expressions work like anonymous methods (a method without a name)

new Runnable() { public void run() { new HelloWorldEvenBetter.setVisible(true); }}

() -> { new HelloWorldEvenBetter.setVisible(true); }

Is thesame as:

So main becomes:

SwingUtilities.invokeLater( () -> { new HelloWorldEvenBetter.setVisible(true);});

Page 25: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Final Version

This is the final version of the“Hello World” GUI program

package example01;import javax.swing.*;

public class HelloWorldEvenBetter extends JFrame {

private JLabel label;

public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); }

private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); }

public static void main(String [] args) { SwingUtilities.invokeLater( () -> { new HelloWorldEvenBetter().setVisible(true); }); }}

HelloWorldEvenBetter.java

Page 26: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Example #2

Demonstrates:

• Setting preferred sizes for objects

• Putting a menu bar in the frame

• Coloring the menu bar

• Adding a big colored label to the content pane

Root Pane

Layered Pane

Content Pane

Menu Bar

JLabel

Page 27: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Things You Need To Know

• You need to create a JMenuBar object

• A Color object is needed to implement colors for various GUI itemsInitialize the Color object with the amount of red, green and blue you want in the colorThe amount is one byte for each == an integer from 0 - 255

• A Dimension object is needed to establish sizesInitialize with the width and the height, in pixels

Page 28: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Start with the Basic Template

package example02;import java.awt.*;import javax.swing.*;

public class TopLevelDemo extends JFrame {

public TopLevelDemo() { initComponents(); setTitle("Top Level Demo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); }

private void initComponents() { }

public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TopLevelDemo().setVisible(true); } }); }}

TopLevelDemo.java

Page 29: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Add Class Variables and Initialization Codeprivate JMenuBar greenMenuBar;private JLabel yellowLabel;

private void initComponents() { greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20));

yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180));

setJMenuBar(greenMenuBar); getContentPane().add(yellowLabel); pack();}

TopLevelDemo

greenMenuBar yellowLabel

Page 30: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Final Version

This is the final version of the“TopLevelDemo” program

package example02;import java.awt.*;import javax.swing.*;

public class TopLevelDemo extends JFrame {

private JMenuBar greenMenuBar; private JLabel yellowLabel; public TopLevelDemo() { initComponents(); setTitle("Top Level Demo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); }

private void initComponents() { greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20));

yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180));

setJMenuBar(greenMenuBar); getContentPane().add(yellowLabel); pack(); }

public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TopLevelDemo().setVisible(true); } }); }}

Page 31: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Layout Managers

• Each container (by default) has a layout manager

• These objects determine the size and position of the components in the container

• Components in the container can provide suggestions about size and alignment, however the layout manager makes the final decision about how items are positioned

• There are four layout managers which are fairly simple to use

• Additional layout managers can be written bycreating a class which implements theLayoutManager interface

Page 32: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Border Layout

• The default manager for all content panes(except JPanel)

• Has five areas for holding components:NORTH, SOUTH, EAST, WEST, CENTER

• All extra space is placed in the center

• Requires you to indicate in which you wantcomponents placed

Page 33: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Box Layout

• Puts components on a single row or column

• Components are not sized beyond their requestedmaximum size

Page 34: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Flow Layout

• Default manager for Jpanel objects

• Sets out components from left to right

• Starts new rows when necessary

Page 35: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Grid Layout

• Displays components in a grid

• Resizes components so they are all equal in size

• Components are added left to right, filling arow before moving on to another row

• When creating, you must specify the number ofdesired rows OR columns. The opposite value isautomatically computed

Page 36: Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Other Choices

Grid Bag Layout

• A sophisticated layout manager with much more control over the grid

• Requires additional objects to help define the pacement of components

Absolute Positioning

• Used when the layout manager is set to null

• Programmer must specify exact position and size for allcomponents