Top Banner
Chapter 19 Graphical User Interfaces
110

Chapter 19 – Graphical User Interfaces. Chapter Goals To use layout managers to arrange user ‑ interface components in a container To become familiar.

Dec 24, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Chapter 19 – Graphical User Interfaces

Page 2: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Chapter Goals To use layout managers to arrange user‑interface

components in a container To become familiar with common user-interface

components, such as radio buttons, check boxes, and menus

To build programs that handle events generated by user‑interface components

To browse the Java documentation effectively

In this chapter, you will learn how to use the most common user-interface components in the Java Swing toolkit, search Java documentation and handle events for interactive graphical programs.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 2

Page 3: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Introduction A graphical user interface (GUI) presents a user-friendly

mechanism for interacting with an application.

Pronounced “GOO-ee”

GUIs are built from GUI components.

A GUI component is an object with which the user interacts via the mouse, the keyboard or another form of input, such as voice recognition.

Here, you’ll learn about many of Java’s so-called Swing GUI components from the javax.swing package.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 3

Page 4: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

IDE Support for GUI Design Many IDEs provide GUI design tools with which you can

specify a component’s exact size and location in a visual manner by using the mouse.

The IDE generates the GUI code for you.

Though this greatly simplifies creating GUIs, each IDE generates this code differently.

For this reason, we will write the GUI code by hand.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 4

Page 5: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Sample Demo Download Swingset3 application and run:

download.java.net/javadesktop/swingset3/SwingSet3.jnlp

This application is a nice way for you to browse through the various GUI components provided by Java’s Swing GUI APIs.

Simply click a component name (e.g., JFrame, JTabbedPane, etc.) in the GUI Components area at the left of the window to see a demonstration of the GUI component in the right side of the window. The source code for each demo is shown in the text area at the bottom of the window.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 5

Page 6: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

From: Java How To Program – Dietel & Dietel

Page 6

The menus, buttons and combo box arepart of the application’s GUI.

They enable you to interact with the application.

Page 7: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Simple GUI-Based Input/Output with JOptionPane

Most applications you use on a daily basis use windows or dialog boxes (also called dialogs) to interact with the user.

Dialog boxes are windows in which programs display important messages to the user or obtain information from the user.

Java’s JOptionPane class (package javax.swing) provides prebuilt dialog boxes for both input and output.

Dialogs are displayed by invoking static JOptionPane methods.

Refer JavaDoc APICopyright © 2014 by John Wiley & Sons. All rights reserved.

Page 7

Page 8: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 8

Page 9: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

null = result in centering message in screen

Unlike Scanner, which can be used to input values of several types from theuser at the keyboard, an input dialog can input only Strings.

If the user clicks Cancel, showInputDialog returns null.

result in centering message in parent component

Page 10: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Programming Question Write a tester program Addition that takes two numbers as user input,

calculate sum and display calculated sum. Use JOptionPane to get user input and display sum.

Sample output is shown below:

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 10

Page 11: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Answer

Page 11

import javax.swing.JOptionPane; // program uses JOptionPane

public class Addition { public static void main( String[] args ) { // obtain user input from JOptionPane input dialogs String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); String secondNumber = JOptionPane.showInputDialog( "Enter second integer" );

// convert String inputs to int values for use in a calculation int number1 = Integer.parseInt( firstNumber ); int number2 = Integer.parseInt( secondNumber );

int sum = number1 + number2; // add numbers

// display result in a JOptionPane message dialog JOptionPane.showMessageDialog( null, "The sum is " + sum, "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE ); } // end method main} // end class Addition

Addition.java

Page 12: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

19.1 Layout Management Arranging components on the screen

User-interface components are arranged by placing them in a Swing Container object:

• Jframe, JPanel

• JFrame = a heavy weight container used as the top-level window

• JPanel = a light weight container used to organize GUI components

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 12

Page 13: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Jfrrame Class Example empty JFrame window:

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 13

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

public class Frame1 { public static void main(String[] args) { JFrame f = new JFrame("My First Frame"); // Create Frame

f.setSize(400,300); // Set size of frame f.setVisible(true); // Show the window } }

Page 14: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Output:

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 14

Page 15: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Example JFrame with a GUI object(Jlabel) added:

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 15

import java.awt.*; import javax.swing.*; public class Frame2 { public static void main(String[] args) { JFrame f = new JFrame("My First GUI"); f.setSize(400,300);

//create a label JLabel L = new JLabel("Hello World !");

//add label to frame f.getContentPane().add( L );

f.setVisible(true); } }

Page 16: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Output:

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 16

Page 17: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

JPanel Class To display the JPanel, the JPanel must be added on to the JFrame !!!

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 17

import java.awt.*; import javax.swing.*; public class Frame3 { public static void main(String[] args) { JFrame f = new JFrame("JFrame with a JPanel"); JLabel L = new JLabel("Hello World !"); // Make a JLabel; JPanel P = new JPanel(); // Make a JPanel; P.add(L); // Add lable L to JPanel P f.getContentPane().add(P); // Add panel P to JFrame f f.setSize(400,300); f.setVisible(true); } }

Page 18: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Output:

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 18

Page 19: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Layout Management Each container has a layout manager that directs

the arrangement of its components Three useful layout managers are:

1) Border layout2) Flow layout3) Grid layout

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 19

Components are added to a container which uses a layout manager to place them

Page 20: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Jframe’s Content Pane

A JFrame has a content pane which is a Container where you can add components

Use the getContentPane method to get its reference

Adding components:

Add components to the content pane OR

Add a container to the content pane, then add components to the container

Container contentPane = getContentPane();

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 20

Page 21: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Jframe’s Content Pane (2) Frame

Menu Bar Content Pane

• Components• Container

– Components

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 21

Frame (with Title Bar)

Content Pane

x

Menu Bar (optional)

Container

Page 22: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Flow Layout Components are added from left to right

A JPanel uses flow layout by default

panel = new JPanel();panel.add(rateLabel);panel.add(rateField);panel.add(button);panel.add(resultLabel)

;

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 22

Page 23: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Example:

Page 23

import java.awt.*; import javax.swing.*; public class FlowLayoutDemo { public static void main(String[] args) { JFrame f = new JFrame("FlowLayoutDemo"); JPanel p = new JPanel(); FlowLayout layout = new FlowLayout(); layout.setHgap(50); layout.setVgap(50); p.setLayout(layout); p.add(new JLabel("One")); p.add(new JLabel("Two")); p.add(new JLabel("Three")); p.add(new JLabel("Four")); p.add(new JLabel("Five")); p.add(new JLabel("Six")); f.getContentPane().add(p); f.setSize(300,300); f.setVisible(true);

} }

Page 24: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Output:

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 24

Page 25: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Border Layout Components are placed toward areas of a

container NORTH, EAST, SOUTH, WEST, or CENTER Specify one when adding components

The content pane of a JFrame uses border layout by default

panel.setLayout(new BorderLayout());panel.add(component,

BorderLayout.NORTH);

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 25

Page 26: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Example

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 26

import java.awt.*; import javax.swing.*; public class BorderLayoutDemo { public static void main(String[] args) { JFrame f = new JFrame("BorderLayout Demo"); JPanel p = new JPanel(); BorderLayout layout = new BorderLayout(); p.setLayout(layout); p.add(new JButton("North"), BorderLayout.NORTH); p.add(new JButton("South") , BorderLayout.SOUTH); p.add(new JButton("West") , BorderLayout.WEST); p.add(new JButton("East") , BorderLayout.EAST); p.add(new JButton("Center") , BorderLayout.CENTER); f.getContentPane().add(p); f.setSize(500,500); f.setVisible(true);

} }

Page 27: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Sometimes we extend JFrame class to do the same:

Page 27

import javax.swing.JFrame;import javax.swing.JPanel;import java.awt.BorderLayout;import javax.swing.JButton;import javax.swing.SwingUtilities;

public class MyJFrame extends JFrame {

public MyJFrame() { setTitle("MyJFrame Example"); setSize(300, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); JPanel p = new JPanel(); BorderLayout layout = new BorderLayout(); p.setLayout(layout); p.add(new JButton("North"), BorderLayout.NORTH); p.add(new JButton("South") , BorderLayout.SOUTH); p.add(new JButton("West") , BorderLayout.WEST); p.add(new JButton("East") , BorderLayout.EAST); p.add(new JButton("Center") , BorderLayout.CENTER); getContentPane().add(p); }

public static void main(String[] args) { MyJFrame ex = new MyJFrame(); ex.setVisible(true); }}

Page 28: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Output:

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 28

Page 29: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Grid Layout Components are placed in boxes in a simple table

arrangement Specify the size (rows then columns) of the grid

Then add components which will be placed from the upper left, across, then down

buttonPanel.add(button7);buttonPanel.add(button8);buttonPanel.add(button9);buttonPanel.add(button4);. . .

JPanel buttonPanel = new JPanel();buttonPanel.setLayout(new GridLayout(4,

3));

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 29

Page 30: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Example:

Page 30

import java.awt.*; import javax.swing.*; public class GridLayoutDemo { public static void main(String[] args) { JFrame f = new JFrame("GridLayout Demo"); JPanel p = new JPanel(); GridLayout layout = new GridLayout(4,3); p.setLayout(layout); p.add(new JButton("7")); p.add(new JButton("8")); p.add(new JButton("9")); p.add(new JButton("4")); p.add(new JButton("5")); p.add(new JButton("6")); p.add(new JButton("1")); p.add(new JButton("2")); p.add(new JButton("3")); p.add(new JButton("0")); p.add(new JButton(".")); p.add(new JButton("CE")); f.getContentPane().add(p); f.setSize(300,300); f.setVisible(true);

} }

Page 31: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Output:

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 31

Page 32: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Using Nested Panels Create complex layouts by nesting panels

Give each panel an appropriate layout manager Panels have invisible borders, so you can use as many

panels as you need to organize components

JPanel keypadPanel = new JPanel();keypadPanel.setLayout(new BorderLayout());buttonPanel = new JPanel();buttonPanel.setLayout(new GridLayout(4, 3));buttonPanel.add(button7);buttonPanel.add(button8);// . . .keypadPanel.add(buttonPanel,

BorderLayout.CENTER);JTextField display = new JTextField();keypadPanel.add(display, BorderLayout.NORTH);

JTextField in NORTH of keypadPanel

JPanel GridLayout in CENTER of keypadPanel

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 32

Page 33: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Example

Page 33

import java.awt.*; import javax.swing.*; public class CalculatorDemo { public static void main(String[] args) { JFrame f = new JFrame("Calculator Demo"); JPanel calculatorPanel = new JPanel(); BorderLayout bLayout = new BorderLayout(); calculatorPanel.setLayout(bLayout); //add display JTextField display = new JTextField(); calculatorPanel.add(display, BorderLayout.NORTH);

//add keypad JPanel keypadPanel = new JPanel(); GridLayout gLayout = new GridLayout(4,3); keypadPanel.setLayout(gLayout); keypadPanel.add(new JButton("7")); keypadPanel.add(new JButton("8")); keypadPanel.add(new JButton("9")); keypadPanel.add(new JButton("4")); keypadPanel.add(new JButton("5")); keypadPanel.add(new JButton("6")); keypadPanel.add(new JButton("1")); keypadPanel.add(new JButton("2")); keypadPanel.add(new JButton("3")); keypadPanel.add(new JButton("0")); keypadPanel.add(new JButton(".")); keypadPanel.add(new JButton("CE")); calculatorPanel.add(keypadPanel, BorderLayout.CENTER); f.getContentPane().add(calculatorPanel); f.setSize(300,300); f.setVisible(true); } }

Page 34: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Output:

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 34

Page 35: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Processing Text Input

Dialog boxes allows for user input… but Popping up a separate dialog box for each input is not a natural

user interface Most graphical programs collect text input through text

fields The JTextField class provides a text field

• When you construct a text field, supply the width:– The approximate number of characters that you expect– If the user exceeds this number, text will ‘scroll’ left

final int FIELD_WIDTH = 10;final JTextField rateField = new

JTextField(FIELD_WIDTH);

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 35

Page 36: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Add a Label and a Button A Label helps the user know what you want

Normally to the left of a textbox

A Button with an actionPerformed method can be used to read the text from the textbox with the getText method Note that getText returns a String, and must be converted to a numeric

value if it will be used in calculations

JLabel rateLabel = new JLabel("Interest Rate: ");

double rate = Double.parseDouble(rateField.getText());double interest = account.getBalance() * rate / 100;account.deposit(interest);resultLabel.setText("balance: " +

account.getBalance());Page 36

Page 37: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Programming Question Write a program InvestmentFrame2 that extends JFrame to

create following GUI. Application assumes an initial balance of $1000 and a default interest

rate of 5%. GUI should let user enter an interest rate. Clicking on “Add Interest

button” should print the updated balance

1. Start by defining constants:1. GUI constants: frame width, frame height

2. Application constants: default rate, initial balance

2. Define variables:1. GUI variables: rate label, rate text field, button, result label

2. Application variables: balance

Page 37

Page 38: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

3. Create the GUI in no-argument constructor. 1. Initialize balance with initial balance

2. Create result label with initial balance

3. calls following 3 methods (you should implement) to implement GUI:– createButton(), createTextField(), createPanel()– createPanel method add all generated GUI comonents to panel.

4. Set size of frame

4. Write an inner class called AddInterestListener that implements ActionListener interface to handle action when button is pressed.

• Class has only one method: public void actionPerformed(ActionEvent event){

//code to get user input rate from GUI, calculate and display new balance

}

• CreateButton method should:– create the button – create object of AddInterestListener (say listener)– Add listener to button:

» button.addActionListener(listener);

• Download templatePage 38

Page 39: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

InvestmentFrame2.java skeleton

Page 39

public class InvestmentFrame2 extends JFrame{ /*** TODO: define constants **/ /*** TODO: define variables **/ //constructor public InvestmentFrame2() {

/*** TODO: initialize balance **//*** TODO: create result label **/ /*** TODO: create text field **//*** TODO: create button **//*** TODO: create panel**//*** TODO: set size of frame **/

}

private void createTextField() {

/*** TODO: create rate label **//*** TODO: create text field with default text **/

}

/** Inner class: Adds interest to the balance and updates the display. */ class AddInterestListener implements ActionListener { public void actionPerformed(ActionEvent event) { /*** TODO: get user, input rate, calculate and display updated balance in result label**/ } } private void createButton() { /*** TODO: create button **/ /*** TODO: create AddInterestActionListener object**/

/*** TODO: add this listener to button**/ }

private void createPanel() { /*** TODO: create panel **/ /*** TODO: GUI components to panel **/ /*** TODO: add panel to frame **/ } }

Page 40: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Test the created GUI using following tester class:

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 40

import javax.swing.JFrame;

/** This program displays the growth of an investment with variable interest.*/public class InvestmentViewer2{ public static void main(String[] args) { JFrame frame = new InvestmentFrame2(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}

Page 41: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Answer

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 41

1 import java.awt.event.ActionEvent;2 import java.awt.event.ActionListener;3 import javax.swing.JButton;4 import javax.swing.JFrame;5 import javax.swing.JLabel;6 import javax.swing.JPanel;7 import javax.swing.JTextField;8 9 /**10 A frame that shows the growth of an investment with variable interest.11*/12public class InvestmentFrame2 extends JFrame13{ 14 private static final int FRAME_WIDTH = 450;15 private static final int FRAME_HEIGHT = 100;1617 private static final double DEFAULT_RATE = 5;18 private static final double INITIAL_BALANCE = 1000; 1920 private JLabel rateLabel;21 private JTextField rateField;22 private JButton button;23 private JLabel resultLabel;24 private double balance;25 26 public InvestmentFrame2()27 { 28 balance = INITIAL_BALANCE;2930 resultLabel = new JLabel("Balance: " + balance);3132 createTextField();33 createButton();34 createPanel();3536 setSize(FRAME_WIDTH, FRAME_HEIGHT);37 }38

InvestmentFrame2.java

Continued

Page 42: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 42

39 private void createTextField()40 {41 rateLabel = new JLabel("Interest Rate: ");4243 final int FIELD_WIDTH = 10;44 rateField = new JTextField(FIELD_WIDTH);45 rateField.setText("" + DEFAULT_RATE);46 }4748 /**49 Adds interest to the balance and updates the display.50 */51 class AddInterestListener implements ActionListener52 {53 public void actionPerformed(ActionEvent event)54 {55 double rate = Double.parseDouble(rateField.getText());56 double interest = balance * rate / 100;57 balance = balance + interest;58 resultLabel.setText("Balance: " + balance);59 } 60 }61 62 private void createButton()63 {64 button = new JButton("Add Interest");65 66 ActionListener listener = new AddInterestListener();67 button.addActionListener(listener);68 }6970 private void createPanel()71 {72 JPanel panel = new JPanel();73 panel.add(rateLabel);74 panel.add(rateField);75 panel.add(button);76 panel.add(resultLabel); 77 add(panel);78 }

Page 43: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Text Areas

Create multi-line text areas with a JTextArea object

Set the size in rows and columns

Use the setText method to set the text of a text field or text area

final int ROWS = 10;final int COLUMNS = 30;JTextArea textArea = new JTextArea(ROWS,

COLUMNS);

textArea.setText(“Account Balance”);

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 43

Page 44: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Text Areas The append method adds text to the end of a text area

• Use newline characters to separate lines

Use the setEditable method to control user input

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 44

textArea.append(account.getBalance() + "\n");

textArea.setEditable(false);

Page 45: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

JTextField and JTextArea JTextField and JTextArea inherit

from JTextComponent: setText setEditable

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 45

Page 46: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

JTextField and JTextArea The append method is declared in the JTextArea class

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 46

To add scroll bars, use JScrollPane:JScrollPane scrollPane = new

JScrollPane(textArea);

Page 47: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Programming Question Modify InvestmentFrame2 (save as InvestmentFrame3) to

replace result label with a text area (with scroll bars). Every time the user clicks button, a new line should be added to text are showing updated total.

Test code:

Page 47

import javax.swing.JFrame;

/** This program displays the growth of an investment. */public class InvestmentViewer3{ public static void main(String[] args) { JFrame frame = new InvestmentFrame3(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}

Page 48: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Answer

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 48

1 import java.awt.event.ActionEvent;2 import java.awt.event.ActionListener;3 import javax.swing.JButton;4 import javax.swing.JFrame;5 import javax.swing.JLabel;6 import javax.swing.JPanel;7 import javax.swing.JScrollPane;8 import javax.swing.JTextArea;9 import javax.swing.JTextField;1011/**12 A frame that shows the growth of an investment with variable interest,13 using a text area.14*/15public class InvestmentFrame3 extends JFrame16{17 private static final int FRAME_WIDTH = 400;18 private static final int FRAME_HEIGHT = 250;19 20 private static final int AREA_ROWS = 10;21 private static final int AREA_COLUMNS = 30;2223 private static final double DEFAULT_RATE = 5;24 private static final double INITIAL_BALANCE = 1000; 25 26 private JLabel rateLabel;27 private JTextField rateField;28 private JButton button;29 private JTextArea resultArea;30 private double balance;31

Continued

InvestmentFrame3.java

Page 49: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 49

32 public InvestmentFrame3()33 { 34 balance = INITIAL_BALANCE;35 resultArea = new JTextArea(AREA_ROWS, AREA_COLUMNS);36 resultArea.setText(balance + "\n");37 resultArea.setEditable(false);38 39 createTextField();40 createButton();41 createPanel();4243 setSize(FRAME_WIDTH, FRAME_HEIGHT);44 }4546 private void createTextField()47 {48 rateLabel = new JLabel("Interest Rate: ");4950 final int FIELD_WIDTH = 10;51 rateField = new JTextField(FIELD_WIDTH);52 rateField.setText("" + DEFAULT_RATE);53 }54

Continued

Page 50: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 50

55 class AddInterestListener implements ActionListener56 {57 public void actionPerformed(ActionEvent event)58 {59 double rate = Double.parseDouble(rateField.getText());60 double interest = balance * rate / 100;61 balance = balance + interest;62 resultArea.append(balance + "\n");63 } 64 }6566 private void createButton()67 {68 button = new JButton("Add Interest"); 69 70 ActionListener listener = new AddInterestListener();71 button.addActionListener(listener);72 }7374 private void createPanel()75 {76 JPanel panel = new JPanel();77 panel.add(rateLabel);78 panel.add(rateField);79 panel.add(button);80 JScrollPane scrollPane = new JScrollPane(resultArea);81 panel.add(scrollPane); 82 add(panel);83 }84}

Page 51: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

19.3 Choices

In a modern graphical user interface program, there are commonly used devices to make different types of selections:

Radio Buttons

• For a small set of mutually exclusive choices

Check Boxes

• For a binary choice

Combo Boxes• For a large set of choices

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 51

Page 52: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

FontViewer Layout Title Bar Label

Shows current font

Combo Box Check Boxes Radio Buttons

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 52

Page 53: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Grouping Radio Buttons Add Radio Buttons into a ButtonGroup so that

only one button in the group is selected at a time Create the JRadioButtons first, then add them to the ButtonGroup

Note that the button group does not place the buttons close to each other on the container

JRadioButton smallButton = new JRadioButton("Small");

JRadioButton mediumButton = new JRadioButton("Medium");

JRadioButton largeButton = new JRadioButton("Large");

ButtonGroup group = new ButtonGroup();group.add(smallButton);group.add(mediumButton);group.add(largeButton);

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 53

Page 54: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Radio Button Panels Use a panel for each set of radio buttons

The default border for a panel is invisible (no border)

You can add a border to a panel to make it visible along with a text label:

There are a large number of border styles available

• See the Swing documentation for more details

JPanel panel = new JPanel();panel.add(smallButton);panel.add(mediumButton);panel.add(largeButton);panel.setBorder(new TitledBorder(new

EtchedBorder(),"Size"));

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 54

Page 55: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Selecting Radio Buttons It is customary to set one button as selected (the

default) when using radio buttons Use the button's setSelected method Set the default button before making the enclosing

frame visible

Call the isSelected method of each button to find out which one it is currently selected

JRadioButton largeButton = new JRadioButton("Large");

largeButton.setSelected(true);

if (largeButton.isSelected()) { size = LARGE_SIZE; }

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 55

Page 56: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Check Boxes versus Radio Buttons Radio buttons and check boxes have different

visual appearances

Radio buttons are round and

show a black dot when selected

Check boxes are square and

show a check mark when selected

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 56

Page 57: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Check Boxes

A check box is a user-interface component with two states: checked and unchecked

• Use for choices that are not mutually exclusive

– For example, text may be Italic, Bold, both or neither

• Because check box settings do not exclude each other, you do not need to place a set of check boxes inside a button group

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 57

Page 58: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Selecting Check Boxes

To setup a Check Box, use Swing JCheckBox Pass the constructor the name for the check box label

Call the isSelected method of a checkbox to find out whether it is currently selected or not

JCheckBox italicCheckBox = new JCheckBox("Italic");

if (italicCheckBox.isSelected()) { style = style + Font.ITALIC }

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 58

Page 59: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Combo Boxes A combo box is a combination of a list and a text

field Use a combo box for a large set of choices

• Use when radio buttons would take up too much space

It can also be editable• Type a selection into a blank line

When you click on the arrow to the right of the text field of a combo box, a list of selections drops down, and you can choose one of the items in the list

facenameCombo.setEditable();

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 59

Page 60: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Adding and Selecting Items Add text ‘items’ to a combo box that will show in

the list:

Use the getSelectedItem method to return the selected item (as an Object) Combo boxes can store other objects in addition to

strings, so casting to a string may be required:

JComboBox facenameCombo = new JComboBox();

facenameCombo.addItem("Serif");facenameCombo.addItem("SansSerif");. . .

String selectedString = (String) facenameCombo.getSelectedItem();

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 60

Page 61: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Programming Question Write a program FontFrame to create the following GUI: The font displayed should change when user select

different choices from combo box, checkboxes and radio buttons E.g. when user selects italics, text “Big Java ” should be displayed in

italics.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 61

Serif, SansSerif, Monospaced

Page 62: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

1. Create constants: frame width and frame height

2. Create variables:1. Label to display font “Big Java”

2. 2 Checkboxes : italics, bold

3. 3 Radiobuttons: small, medium, large

4. Combobox for font face name (Serif, SansSerif, Monospaced)

5. ActionListener to change display text based on user selections

3. Define no argument constructor1. Construct label with text “Big Java”

2. Add label to BorderLayout.CENTER

3. createControlPanel() : create checkboxes, radiobuttons, comboboxes add it to BorderLayout.SOUTH.

4. Set label font

5. Set size

4. Implement nested class ChoiceListener that implements ActionListener1. Actionperformed method will set the label font to current user choices

Download templatePage 62

Page 63: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Test FontFrame class using following Tester class:

Page 63

import javax.swing.JFrame;

/** This program allows the user to view font effects.*/public class FontViewer{ public static void main(String[] args) { JFrame frame = new FontFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("FontViewer"); frame.setVisible(true); }}

Page 64: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Answer1 import java.awt.BorderLayout;2 import java.awt.Font;3 import java.awt.GridLayout;4 import java.awt.event.ActionEvent;5 import java.awt.event.ActionListener;6 import javax.swing.ButtonGroup;7 import javax.swing.JButton;8 import javax.swing.JCheckBox;9 import javax.swing.JComboBox;10 import javax.swing.JFrame;11 import javax.swing.JLabel;12 import javax.swing.JPanel;13 import javax.swing.JRadioButton;14 import javax.swing.border.EtchedBorder;15 import javax.swing.border.TitledBorder;16 17 /**18 This frame contains a text sample and a control panel19 to change the font of the text.20 */21 public class FontFrame extends JFrame22 {23 private static final int FRAME_WIDTH = 300;24 private static final int FRAME_HEIGHT = 400;25 26 private JLabel label;27 private JCheckBox italicCheckBox;28 private JCheckBox boldCheckBox;29 private JRadioButton smallButton;30 private JRadioButton mediumButton;31 private JRadioButton largeButton;32 private JComboBox facenameCombo;33 private ActionListener listener;34 Page 64

FontFrame.java

Continued

Page 65: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Page 65

35 /**36 Constructs the frame.37 */38 public FontFrame()39 { 40 // Construct text sample41 label = new JLabel("Big Java");42 add(label, BorderLayout.CENTER);43 44 // This listener is shared among all components45 listener = new ChoiceListener();46 47 createControlPanel();48 setLabelFont();49 setSize(FRAME_WIDTH, FRAME_HEIGHT);50 }51 52 class ChoiceListener implements ActionListener53 { 54 public void actionPerformed(ActionEvent event)55 { 56 setLabelFont();57 }58 }59

Continued

Page 66: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

60 /**61 Creates the control panel to change the font.62 */63 public void createControlPanel()64 {65 JPanel facenamePanel = createComboBox();66 JPanel sizeGroupPanel = createCheckBoxes();67 JPanel styleGroupPanel = createRadioButtons();68 69 // Line up component panels70 71 JPanel controlPanel = new JPanel();72 controlPanel.setLayout(new GridLayout(3, 1));73 controlPanel.add(facenamePanel);74 controlPanel.add(sizeGroupPanel);75 controlPanel.add(styleGroupPanel);76 77 // Add panels to content pane78 79 add(controlPanel, BorderLayout.SOUTH);80 }81 82 /**83 Creates the combo box with the font style choices.84 @return the panel containing the combo box85 */86 public JPanel createComboBox()87 {88 facenameCombo = new JComboBox();89 facenameCombo.addItem("Serif");90 facenameCombo.addItem("SansSerif");91 facenameCombo.addItem("Monospaced");92 facenameCombo.setEditable(true);93 facenameCombo.addActionListener(listener);94 95 JPanel panel = new JPanel();96 panel.add(facenameCombo);97 return panel;98 }

Page 66

Continued

Page 67: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

99 100 /**101 Creates the check boxes for selecting bold and italic styles.102 @return the panel containing the check boxes103 */104 public JPanel createCheckBoxes()105 {106 italicCheckBox = new JCheckBox("Italic");107 italicCheckBox.addActionListener(listener);108109 boldCheckBox = new JCheckBox("Bold");110 boldCheckBox.addActionListener(listener);111112 JPanel panel = new JPanel();113 panel.add(italicCheckBox);114 panel.add(boldCheckBox);115 panel.setBorder(new TitledBorder(new EtchedBorder(), "Style"));116117 return panel;118 }119

Page 67

Continued

Page 68: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

120 /**121 Creates the radio buttons to select the font size.122 @return the panel containing the radio buttons123 */124 public JPanel createRadioButtons()125 {126 smallButton = new JRadioButton("Small");127 smallButton.addActionListener(listener);128129 mediumButton = new JRadioButton("Medium");130 mediumButton.addActionListener(listener);131132 largeButton = new JRadioButton("Large");133 largeButton.addActionListener(listener);134 largeButton.setSelected(true);135136 // Add radio buttons to button group137138 ButtonGroup group = new ButtonGroup();139 group.add(smallButton);140 group.add(mediumButton);141 group.add(largeButton);142143 JPanel panel = new JPanel();144 panel.add(smallButton);145 panel.add(mediumButton);146 panel.add(largeButton);147 panel.setBorder(new TitledBorder(new EtchedBorder(), "Size"));148149 return panel;150 }

Page 68

Continued

Page 69: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

151152 /**153 Gets user choice for font name, style, and size154 and sets the font of the text sample.155 */156 public void setLabelFont()157 { 158 // Get font name 159 String facename = (String) facenameCombo.getSelectedItem();160 161 // Get font style162 163 int style = 0;164 if (italicCheckBox.isSelected()) 165 { 166 style = style + Font.ITALIC; 167 }168 if (boldCheckBox.isSelected()) 169 { 170 style = style + Font.BOLD; 171 }172 173 // Get font size 174175 int size = 0;176 177 final int SMALL_SIZE = 24;178 final int MEDIUM_SIZE = 36;179 final int LARGE_SIZE = 48;180181 if (smallButton.isSelected()) { size = SMALL_SIZE; }182 else if (mediumButton.isSelected()) { size = MEDIUM_SIZE; }183 else if (largeButton.isSelected()) { size = LARGE_SIZE; }184 185 // Set font of text field186 187 label.setFont(new Font(facename, style, size)); 188 label.repaint();189 }190 }

Page 69

Page 70: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Steps to Design a User Interface

1) Make a sketch of the component layout.

Draw all the buttons, labels, text fields, and borders on a sheet of graph paper

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 70

Page 71: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Steps to Design a User Interface2) Find groupings of adjacent components with the same

layout.

Start by looking at adjacent components that are arranged top to bottom or left to right

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 71

Page 72: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Steps to Design a User Interface

3) Identify layouts for each group. For horizontal components, use flow Layout For vertical components, use a grid layout with one

column

4) Group the groups together. Look at each group as one blob, and group the blobs

together into larger groups, just as you grouped the components in the preceding step

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 72

Page 73: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Steps to Design a User Interface5) Write the code to generate the layout

JPanel radioButtonPanel = new JPanel();radioButtonPanel.setLayout(new GridLayout(3, 1));radioButton.setBorder(new TitledBorder(new EtchedBorder(), "Size"));radioButtonPanel.add(smallButton);radioButtonPanel.add(mediumButton);radioButtonPanel.add(largeButton);

JPanel checkBoxPanel = new JPanel();checkBoxPanel.setLayout(new GridLayout(2, 1));checkBoxPanel.add(pepperoniButton());checkBoxPanel.add(anchoviesButton());

JPanel pricePanel = new JPanel(); // Uses FlowLayout by defaultpricePanel.add(new JLabel("Your Price:"));pricePanel.add(priceTextField);

JPanel centerPanel = new JPanel(); // Uses FlowLayoutcenterPanel.add(radioButtonPanel);centerPanel.add(checkBoxPanel); // Frame uses BorderLayout by

default

add(centerPanel, BorderLayout.CENTER);add(pricePanel, BorderLayout.SOUTH);

Page 73

Page 74: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

19.4 Menus A frame can contain a menu bar

Menu items can be added to each Menu or subMenu

public class MyFrame extends JFrame{ public MyFrame() { JMenuBar menuBar = new

JMenuBar(); setJMenuBar(menuBar); . . . } . . .}Copyright © 2014 by John Wiley & Sons. All rights reserved.

Page 74

Instantiate a menu bar, then add it to the frame with the setJMenuBar method.

Page 75: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

MenuBar and Menu Items The MenuBar contains Menus

The container for the top-level Menu items is called a MenuBar• Add JMenu objects to the MenuBar

A Menu contains SubMenus and Menu items• A Menu item has no further SubMenus• You add Menu items and SubMenus with the add method

JMenuBar menuBar = new JMenuBar();JMenu fileMenu = new JMenu("File");JMenu fontMenu = new JMenu("Font");menuBar.add(fileMenu);menuBar.add(fontMenu);

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 75

Page 76: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Menu Item Events

Menu items generate action events when selected

Add action listeners only to menu items

• Not to menus or the menu bar

• When the user clicks on a menu name and a submenu opens, no action event is sent

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 76

Page 77: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Menu Item Events

Add action listeners to each Menu item

The listener is customized for each Menu item

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 77

ActionListener listener = new ExitItemListener();

exitItem.addActionListener(listener);

Page 78: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

FaceEvent ActionListener (2)

Listener Inner Class version

Page 78

public JMenuItem createFaceItem(final String name)// Final variables can be accessed from an inner class method{ class FaceItemListener implements ActionListener { public void actionPerformed(ActionEvent event) { facename = name; // Accesses the local variable name setLabelFont(); } } JMenuItem item = new JMenuItem(name); ActionListener listener = new FaceItemListener(); item.addActionListener(listener); return item;}

Page 79: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

1 import java.awt.BorderLayout;2 import java.awt.Font;3 import java.awt.event.ActionEvent;4 import java.awt.event.ActionListener;5 import javax.swing.JFrame;6 import javax.swing.JLabel;7 import javax.swing.JMenu;8 import javax.swing.JMenuBar;9 import javax.swing.JMenuItem;10 11 /**12 This frame has a menu with commands to change the font 13 of a text sample.14 */15 public class FontFrame2 extends JFrame16 {17 private static final int FRAME_WIDTH = 300;18 private static final int FRAME_HEIGHT = 400;19 20 private JLabel label;21 private String facename;22 private int fontstyle;23 private int fontsize;24 25 /**26 Constructs the frame.27 */

Page 79

Continued

Page 80: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

28 public FontFrame2()29 { 30 // Construct text sample 31 label = new JLabel("Big Java");32 add(label, BorderLayout.CENTER);33 34 // Construct menu 35 JMenuBar menuBar = new JMenuBar(); 36 setJMenuBar(menuBar);37 menuBar.add(createFileMenu());38 menuBar.add(createFontMenu());39 40 facename = "Serif";41 fontsize = 24;42 fontstyle = Font.PLAIN;43 44 setLabelFont();45 setSize(FRAME_WIDTH, FRAME_HEIGHT);46 }47 48 class ExitItemListener implements ActionListener49 {50 public void actionPerformed(ActionEvent event)51 {52 System.exit(0);53 }54 } 55

Page 80

Continued

Page 81: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

56 /**57 Creates the File menu.58 @return the menu59 */60 public JMenu createFileMenu()61 {62 JMenu menu = new JMenu("File");63 JMenuItem exitItem = new JMenuItem("Exit"); 64 ActionListener listener = new ExitItemListener();65 exitItem.addActionListener(listener);66 menu.add(exitItem);67 return menu;68 }69 70 /**71 Creates the Font submenu.72 @return the menu73 */74 public JMenu createFontMenu()75 {76 JMenu menu = new JMenu("Font");77 menu.add(createFaceMenu());78 menu.add(createSizeMenu());79 menu.add(createStyleMenu());80 return menu;81 } 82 83 /**84 Creates the Face submenu.85 @return the menu86 */87 public JMenu createFaceMenu()88 {89 JMenu menu = new JMenu("Face");90 menu.add(createFaceItem("Serif"));91 menu.add(createFaceItem("SansSerif"));92 menu.add(createFaceItem("Monospaced"));93 return menu;94 }

Page 81

Continued

Page 82: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

95 96 /**97 Creates the Size submenu.98 @return the menu99 */100 public JMenu createSizeMenu()101 {102 JMenu menu = new JMenu("Size");103 menu.add(createSizeItem("Smaller", -1));104 menu.add(createSizeItem("Larger", 1));105 return menu;106 } 107108 /**109 Creates the Style submenu.110 @return the menu111 */112 public JMenu createStyleMenu()113 {114 JMenu menu = new JMenu("Style");115 menu.add(createStyleItem("Plain", Font.PLAIN));116 menu.add(createStyleItem("Bold", Font.BOLD));117 menu.add(createStyleItem("Italic", Font.ITALIC));118 menu.add(createStyleItem("Bold Italic", Font.BOLD+ Font.ITALIC));120 return menu;121 } 122

Page 82

Continued

Page 83: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

123 /**124 Creates a menu item to change the font face and set its action listener.125 @param name the name of the font face126 @return the menu item127 */128 public JMenuItem createFaceItem(final String name)129 {130 class FaceItemListener implements ActionListener131 {132 public void actionPerformed(ActionEvent event)133 {134 facename = name;135 setLabelFont();136 }137 } 138139 JMenuItem item = new JMenuItem(name); 140 ActionListener listener = new FaceItemListener();141 item.addActionListener(listener);142 return item;143 }144

Page 83

Continued

Page 84: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

145 /**146 Creates a menu item to change the font size147 and set its action listener.148 @param name the name of the menu item149 @param increment the amount by which to change the size150 @return the menu item151 */152 public JMenuItem createSizeItem(String name, final int increment)153 {154 class SizeItemListener implements ActionListener155 {156 public void actionPerformed(ActionEvent event)157 {158 fontsize = fontsize + increment;159 setLabelFont();160 }161 } 162 163 JMenuItem item = new JMenuItem(name); 164 ActionListener listener = new SizeItemListener();165 item.addActionListener(listener);166 return item;167 }

Page 84

Continued

Page 85: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

168169 /**170 Creates a menu item to change the font style171 and set its action listener.172 @param name the name of the menu item173 @param style the new font style174 @return the menu item175 */176 public JMenuItem createStyleItem(String name, final int style)177 {178 class StyleItemListener implements ActionListener179 {180 public void actionPerformed(ActionEvent event)181 {182 fontstyle = style;183 setLabelFont();184 }185 } 186187 JMenuItem item = new JMenuItem(name); 188 ActionListener listener = new StyleItemListener();189 item.addActionListener(listener);190 return item;191 }192193 /**194 Sets the font of the text sample.195 */196 public void setLabelFont()197 { 198 Font f = new Font(facename, fontstyle, fontsize);199 label.setFont(f);200 }201} Page 85

Try it: ch19/section_4

Page 86: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

JDesktopPane and JInternalFrame Allow you to display child windows inside main/parent windows

Create Desktop pane inside JFrame:

Create an internal frame:

or define a class that extend JInternalFrame and then:

JInternalFrame internalFrame = new LoginInternalFrame();

Add internal frame to Desktop pane:

Page 86

JDesktopPane theDesktop;theDesktop = new JDesktopPane(); add( theDesktop ); // add desktop pane to JFrame

JInternalFrame internalFrame = new JInternalFrame("Internal Frame", true, true, true, true );

theDesktop.add( internalFrame ); // attach internal frame

Page 87: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 87

Page 88: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Programming Question Create a Jframe MainMenuFrame with a menu “File” that has a menu

item “Acess Internal Frame”. Clicking on this should create and display a internal frame

(JInternalFrame) displaying text “sample text” So the JInternalFrame should be created inside JMenuItem listener actionperformed

method Clicking on close button should close the internal frame. Write a main method to test your code.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 88

Page 89: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Answer1 import java.awt.BorderLayout;2 import java.awt.Dimension;3 import java.awt.Graphics;4 import java.awt.event.ActionListener;5 import java.awt.event.ActionEvent;6 import java.util.Random;7 import javax.swing.JFrame;8 import javax.swing.JDesktopPane;9 import javax.swing.JMenuBar;10import javax.swing.JMenu;11import javax.swing.JMenuItem;12import javax.swing.JInternalFrame;13import javax.swing.JPanel;14import javax.swing.JLabel;15import javax.swing.ImageIcon;1617public class MainMenuFrame extends JFrame 18{19 private JDesktopPane theDesktop;20

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 89

Continued

Page 90: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

21 // set up GUI22 public MainMenuFrame()23 {24 super( "Using a JDesktopPane" );2526 JMenuBar bar = new JMenuBar(); // create menu bar27 JMenu addMenu = new JMenu( "File" ); // create Add menu28 JMenuItem accessMenuItem = new JMenuItem( "AcessInternalFrame" );2930 addMenu.add( accessMenuItem ); // add new frame item to Add menu31 bar.add( addMenu ); // add Add menu to menu bar32 setJMenuBar( bar ); // set menu bar for this application3334 theDesktop = new JDesktopPane(); // create desktop pane35 add( theDesktop ); // add desktop pane to frame36

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 90

Continued

Page 91: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

37 // set up listener for newFrame menu item38 accessMenuItem.addActionListener(3940 new ActionListener() // anonymous inner class41 { 42 // display new internal window43 public void actionPerformed( ActionEvent event ) 44 {45 // create internal frame46 JInternalFrame internalFrame = new JInternalFrame("Internal Frame", true, true, true, true );47 internalFrame.setTitle("Sample Internal Frame");48 internalFrame.setSize(500, 500);49 internalFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);50 JPanel p = new JPanel(); 51 p.add(new JLabel("sample text"));52 53 internalFrame.getContentPane().add(p);54 55 internalFrame.add( p, BorderLayout.CENTER ); // add panel56 internalFrame.pack(); // set internal frame to size of contents5758 theDesktop.add( internalFrame ); // attach internal frame59 internalFrame.setVisible( true ); // show internal frame60 } 61 } 62 );63 } 64

Page 91

Continued

Page 92: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

65 public static void main( String[] args )66 { 67 MainMenuFrame mainMenuFrame = new MainMenuFrame(); 68 mainMenuFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );69 mainMenuFrame.setSize( 600, 480 ); // set frame size70 mainMenuFrame.setVisible( true ); // display frame71 } 72}

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 92

Page 93: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Creating Password Text Create variable of type JPasswordField field:

JPasswordField passwordField;

Create JPasswordField object:passwordField = new JPasswordField( "Hidden text" );

Add ActionListner:passwordField.addActionListener( listener);

listener should check user name and password typed in by user matches entry in a password database or file.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 93

Page 94: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Programming Question Create a main menu with one menu(File) and one menu item (Login). Clicking on the login button should display a Internal frame for login

implement LoginInternalFrame that extends InternaFrame The Login button should validate user against a logins.txt and display message

“successful login” or “unsuccessful login”

Hint:

Page 94

Page 95: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Answerimport java.awt.BorderLayout;import java.awt.Dimension;import java.awt.Graphics;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.util.Random;import javax.swing.JFrame;import javax.swing.JDesktopPane;import javax.swing.JMenuBar;import javax.swing.JMenu;import javax.swing.JMenuItem;import javax.swing.JInternalFrame;import javax.swing.JPanel;import javax.swing.JLabel;import javax.swing.ImageIcon;

public class MainMenuFrame2 extends JFrame { private JDesktopPane theDesktop;

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 95

MainMenuFrame2.java

Continued

Page 96: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

// set up GUI public MainMenuFrame2() { super( "Student Registration System" );

JMenuBar bar = new JMenuBar(); // create menu bar JMenu addMenu = new JMenu( "File" ); // create Add menu JMenuItem loignMenuItem = new JMenuItem( "Login" );

addMenu.add( loignMenuItem ); // add new frame item to Add menu bar.add( addMenu ); // add Add menu to menu bar setJMenuBar( bar ); // set menu bar for this application

theDesktop = new JDesktopPane(); // create desktop pane add( theDesktop ); loignMenuItem.addActionListener(// set up listener for newFrame menu item

new ActionListener() // anonymous inner class { // display new internal window public void actionPerformed( ActionEvent event ) { // create internal frame JInternalFrame internalFrame = new LoginInternalFrame(); internalFrame.setSize(500, 500); internalFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); internalFrame.pack(); // set internal frame to size of contents

theDesktop.add( internalFrame); // attach internal frame internalFrame.setVisible( true ); // show internal frame } } ); }

Page 96

Continued

Page 97: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

public static void main( String[] args ) { MainMenuFrame2 mainMenuFrame = new MainMenuFrame2(); mainMenuFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); mainMenuFrame.setSize( 600, 480 ); // set frame size mainMenuFrame.setVisible( true ); // display frame } }

Page 97

Page 98: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Page 98

import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JButton;import javax.swing.JTextField;import javax.swing.JPasswordField;import javax.swing.JOptionPane;import javax.swing.JInternalFrame;import java.util.Scanner;import java.awt.GridLayout;import java.io.File;import java.util.Arrays;

public class LoginInternalFrame extends JInternalFrame { private JLabel userLabel; //user label private JTextField userTextField; // user text filed private JLabel passwordLabel; //user label private JPasswordField passwordField; // password field with text private JButton loginButton; //login button private JButton cancelButton; //cancel button String userName; char[] password;

LoginInternalFrame.java

Continued

Page 99: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Page 99

public LoginInternalFrame() { super("Login", true, true, true, true ); //setTitle("Login"); setLayout( new GridLayout(3,2) ); userLabel = new JLabel("User Name: "); passwordLabel = new JLabel("Password: "); userTextField = new JTextField( 10 ); passwordField = new JPasswordField( 10 ); loginButton = new JButton("Login"); cancelButton = new JButton("Cancel"); getContentPane().add(userLabel); getContentPane().add(userTextField); getContentPane().add(passwordLabel); getContentPane().add(passwordField); getContentPane().add(loginButton); getContentPane().add(cancelButton); LoginHandler handler = new LoginHandler(); loginButton.addActionListener( handler ); cancelButton.addActionListener( handler ); }

Continued

Page 100: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Page 100

private class LoginHandler implements ActionListener { // process textfield events public void actionPerformed( ActionEvent event ) {

if ( event.getSource() == loginButton ) { userName = userTextField.getText(); password = passwordField.getPassword(); boolean foundMatch = false; try { Scanner sc = new Scanner(new File("logins.txt")); while(sc.hasNext() && !foundMatch) { String[] entry = sc.next().split(","); System.out.println("user: "+userName+ " entry[0]: "+entry[0]); System.out.println("password: "+password+ " entry[1]: "+entry[1]); if( Arrays.equals (entry[0].toCharArray(), userName.toCharArray()) && Arrays.equals

(entry[1].toCharArray(), password)) { foundMatch = true; break; } }

Continued

Page 101: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Page 101

if(!foundMatch) { JOptionPane.showMessageDialog( null, "Unsuccessful Login","Failed Login",

JOptionPane.ERROR_MESSAGE ); userTextField.setText(""); passwordField.setText(""); } else { JOptionPane.showMessageDialog( null, "Successful Login","Successful Login",

JOptionPane.INFORMATION_MESSAGE ); setClosed( true ); } } catch(Exception e) { e.printStackTrace(); } } else if( event.getSource() == cancelButton ) { setVisible(false); } } } }

Page 102: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Project: Your project main menu window should ideally have only login menu item enabled. A User first select login menu item and login. Upon successful login, other menu items (register for course, enter grades etc.) should

be enabled. You can provide role based access to each user by also keeping a separate file:

• Sample entries:Tim, professor

James, Student

If Tim logs in successfully, for example, only certain menu items are enabled.• Enable enter grades menu item• Disable register for classes menu item

You can maintain a separate file which specify allowed operation for each role:• Sample entries:

professor: enterGrades,

student: registerSection, printGrades

Log off button can save what he did to necessary files and reset main menu frame to only enable login menu item.

Page 102

Page 103: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

JLists A list displays a series of items from which

the user may select one or more items created with class JList supports :

Single-selection lists• allow only one item to be selected at a time

Multiple-selection lists• allow any number of items to be selected

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 103

Page 104: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

// ListFrame.javaimport java.awt.FlowLayout;import java.awt.Color;import javax.swing.JFrame;import javax.swing.JList;import javax.swing.JScrollPane;import javax.swing.event.ListSelectionListener;import javax.swing.event.ListSelectionEvent;import javax.swing.ListSelectionModel;

public class ListFrame extends JFrame { private JList colorJList; // list to display colors private static final String[] colorNames = { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow" }; private static final Color[] colors = { Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW };

Page 104

ListFrame.java

Continued

Page 105: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

public ListFrame() { super( "List Test" ); setLayout( new FlowLayout() ); // set frame layout

colorJList = new JList( colorNames ); // create with colorNames colorJList.setVisibleRowCount( 5 ); // display five rows at once // do not allow multiple selections colorJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );

// add a JScrollPane containing JList to frame add( new JScrollPane( colorJList ) );

colorJList.addListSelectionListener( new ListSelectionListener() // anonymous inner class { // handle list selection events public void valueChanged( ListSelectionEvent event ) { getContentPane().setBackground( colors[ colorJList.getSelectedIndex() ] ); } // end method valueChanged } // end anonymous inner class ); // end call to addListSelectionListener } // end ListFrame constructor} // end class ListFrame

Page 105

Page 106: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

JTabbedPane Arranges GUI components into layers, of which only one is

visible at a time. Users access each layer via a tab When the user clicks a tab, the appropriate layer is

displayed. The tabs appear at the top by default Any component can be placed on a tab.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 106

Page 107: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

import java.awt.BorderLayout;import java.awt.Color;import javax.swing.JFrame;import javax.swing.JTabbedPane;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JButton;import javax.swing.SwingConstants;

public class JTabbedPaneFrame extends JFrame { // set up GUI public JTabbedPaneFrame() { super( "JTabbedPane Demo " ); JTabbedPane tabbedPane = new JTabbedPane(); // create JTabbedPane

// set up pane11 and add it to JTabbedPane JLabel label1 = new JLabel( "panel one", SwingConstants.CENTER ); JPanel panel1 = new JPanel(); // create first panel panel1.add( label1 ); // add label to panel tabbedPane.addTab( "Tab One", null, panel1, "First Panel" ); // set up panel2 and add it to JTabbedPane JLabel label2 = new JLabel( "panel two", SwingConstants.CENTER ); JPanel panel2 = new JPanel(); // create second panel panel2.add( label2 ); // add label to panel tabbedPane.addTab( "Tab Two", null, panel2, "Second Panel" );

Page 107

JTabbedPaneFrame.java

Continued

Page 108: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

// set up panel3 and add it to JTabbedPane JLabel label3 = new JLabel( "panel three" ); JPanel panel3 = new JPanel(); // create third panel panel3.setLayout( new BorderLayout() ); // use borderlayout panel3.add( new JButton( "North" ), BorderLayout.NORTH ); panel3.add( new JButton( "West" ), BorderLayout.WEST ); panel3.add( new JButton( "East" ), BorderLayout.EAST ); panel3.add( new JButton( "South" ), BorderLayout.SOUTH ); panel3.add( label3, BorderLayout.CENTER ); tabbedPane.addTab( "Tab Three", null, panel3, "Third Panel" );

add( tabbedPane ); // add JTabbedPane to frame } // end JTabbedPaneFrame constructor}

Page 108

Page 109: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Copyright © 2014 by John Wiley & Sons. All rights reserved.Page 109

import javax.swing.JFrame;

public class JTabbedPaneDemo{ public static void main( String[] args ) { JTabbedPaneFrame tabbedPaneFrame = new JTabbedPaneFrame(); tabbedPaneFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); tabbedPaneFrame.setSize( 300, 300 ); // set frame size tabbedPaneFrame.setVisible( true ); // display frame } // end main} // end class JTabbedPaneDemo

JTabbedPaneDemo.java

Page 110: Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.

Find out more:

BoxLayout

GridBagLayout

Jpopup menus

Page 110