www.users.csbsju.edu

Download Report

Transcript www.users.csbsju.edu

Chapter 19 – Graphical User
Interfaces
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
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
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
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
From: Java How To
Program – Dietel &
Dietel
The menus, buttons
and combo box are
part of the
application’s GUI.
They enable you to
interact with the
application.
Page 6
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 API
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 7
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 8
Unlike Scanner, which can be used to input values of several types from the
user at the keyboard, an input dialog can input only Strings.
If the user clicks Cancel, showInputDialog returns null.
null = result in centering message in screen
result in centering message in parent component
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
Answer
Addition.java
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
Page 11
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
Jfrrame Class

Example empty JFrame window:
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
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 13

Output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 14

Example JFrame with a GUI object(Jlabel) added:
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);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 15

Output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 16
JPanel Class

To display the JPanel, the JPanel must be added on to the JFrame !!!
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 !");
JPanel P = new JPanel();
// Make a JLabel;
// 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);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 17

Output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 18
Layout Management
 Each container has a layout manager that directs
the arrangement of its components
 Three useful layout managers are:
1) Border layout
2) Flow layout
3) Grid layout
Components are added to a
container which uses a layout
manager to place them
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 19
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
Container contentPane = getContentPane();

Adding components:
 Add components to the content pane OR
 Add a container to the content pane, then add
components to the container
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 20
Jframe’s Content Pane (2)

Frame
 Menu Bar
 Content Pane
• Components
• Container
– Components
Frame (with Title Bar)
x
Menu Bar (optional)
Container
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Content Pane
Page 21
Flow Layout

Components are added from left to right
panel = new JPanel();
panel.add(rateLabel);
panel.add(rateField);
panel.add(button);
panel.add(resultLabel);
 A JPanel uses flow layout by default
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 22

Example:
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
p.add(new
p.add(new
p.add(new
p.add(new
p.add(new
JLabel("One"));
JLabel("Two"));
JLabel("Three"));
JLabel("Four"));
JLabel("Five"));
JLabel("Six"));
f.getContentPane().add(p);
f.setSize(300,300);
f.setVisible(true);
}
}
Page 23

Output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 24
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

Example
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
p.add(new
p.add(new
p.add(new
p.add(new
JButton("North"), BorderLayout.NORTH);
JButton("South") , BorderLayout.SOUTH);
JButton("West") , BorderLayout.WEST);
JButton("East") , BorderLayout.EAST);
JButton("Center") , BorderLayout.CENTER);
f.getContentPane().add(p);
f.setSize(500,500);
f.setVisible(true);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 26

Sometimes we extend JFrame class to do the same:
import
import
import
import
import
javax.swing.JFrame;
javax.swing.JPanel;
java.awt.BorderLayout;
javax.swing.JButton;
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 27

Output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 28
Grid Layout

Components are placed in boxes in a simple table
arrangement
 Specify the size (rows then columns) of the grid
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 3));
 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);
. . .
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 29

Example:
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
p.add(new
p.add(new
p.add(new
p.add(new
p.add(new
p.add(new
p.add(new
p.add(new
p.add(new
p.add(new
p.add(new
JButton("7"));
JButton("8"));
JButton("9"));
JButton("4"));
JButton("5"));
JButton("6"));
JButton("1"));
JButton("2"));
JButton("3"));
JButton("0"));
JButton("."));
JButton("CE"));
f.getContentPane().add(p);
f.setSize(300,300);
f.setVisible(true);
}
}
Page 30

Output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 31
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
JTextField in NORTH of keypadPanel
JPanel GridLayout in CENTER of keypadPanel
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);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 32
import java.awt.*;
import javax.swing.*;

Example
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 33

Output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 34
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
Add a Label and a Button

A Label helps the user know what you want
 Normally to the left of a textbox
JLabel rateLabel = new JLabel("Interest Rate: ");

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
double rate = Double.parseDouble(rateField.getText());
double interest = account.getBalance() * rate / 100;
account.deposit(interest);
resultLabel.setText("balance: " + account.getBalance());
Page 36
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.
2.
GUI constants: frame width, frame height
Application constants: default rate, initial balance
2. Define variables:
1.
2.
GUI variables: rate label, rate text field, button, result label
Application variables: balance
Page 37
3. Create the GUI in no-argument constructor.
1.
2.
3.
Initialize balance with initial balance
Create result label with initial balance
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 template
Page 38
InvestmentFrame2.java skeleton
public class InvestmentFrame2 extends JFrame
{
/*** TODO: define constants **/
/*** TODO: define variables **/
//constructor
public InvestmentFrame2()
{
/***
/***
/***
/***
/***
/***
TODO:
TODO:
TODO:
TODO:
TODO:
TODO:
initialize balance **/
create result label **/
create text field **/
create button **/
create panel**/
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 39

Test the created GUI using following tester
class:
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);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 40
Answer
InvestmentFrame2.java
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 JFrame
13{
14
private static final int FRAME_WIDTH = 450;
15
private static final int FRAME_HEIGHT = 100;
16
17
private static final double DEFAULT_RATE = 5;
18
private static final double INITIAL_BALANCE = 1000;
19
20
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;
29
30
resultLabel = new JLabel("Balance: " + balance);
31
32
createTextField();
33
createButton();
34
createPanel();
35
36
setSize(FRAME_WIDTH, FRAME_HEIGHT);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
37
}
38
Continued 
Page 41
39
private void createTextField()
40
{
41
rateLabel = new JLabel("Interest Rate: ");
42
43
final int FIELD_WIDTH = 10;
44
rateField = new JTextField(FIELD_WIDTH);
45
rateField.setText("" + DEFAULT_RATE);
46
}
47
48
/**
49
Adds interest to the balance and updates the display.
50
*/
51
class AddInterestListener implements ActionListener
52
{
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
}
69
70
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);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
77
add(panel);
78
}
Page 42
Text Areas

Create multi-line text areas with a JTextArea object
 Set the size in rows and columns
final int ROWS = 10;
final int COLUMNS = 30;
JTextArea textArea = new JTextArea(ROWS, COLUMNS);
 Use the setText method to set the text of a text field or
text area
textArea.setText(“Account Balance”);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 43
Text Areas
 The append method adds text to the end of a text area
• Use newline characters to separate lines
textArea.append(account.getBalance() + "\n");
 Use the setEditable method to control user input
textArea.setEditable(false);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 44
JTextField and JTextArea

JTextField and JTextArea inherit
from JTextComponent:
 setText
 setEditable
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 45
JTextField and JTextArea


The append method is declared in the
JTextArea class
To add scroll bars, use JScrollPane:
JScrollPane scrollPane = new JScrollPane(textArea);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 46
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:
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 47
Answer
InvestmentFrame3.java
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;
10
11/**
12
A frame that shows the growth of an investment with variable interest,
13
using a text area.
14*/
15public class InvestmentFrame3 extends JFrame
16{
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;
22
23
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;
30Copyright
private
© 2014
double
by Johnbalance;
Wiley & Sons. All rights reserved.
31
Continued 
Page 48
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public InvestmentFrame3()
{
balance = INITIAL_BALANCE;
resultArea = new JTextArea(AREA_ROWS, AREA_COLUMNS);
resultArea.setText(balance + "\n");
resultArea.setEditable(false);
createTextField();
createButton();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createTextField()
{
rateLabel = new JLabel("Interest Rate: ");
final int FIELD_WIDTH = 10;
rateField = new JTextField(FIELD_WIDTH);
rateField.setText("" + DEFAULT_RATE);
}
Continued 
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 49
55
class AddInterestListener implements ActionListener
56
{
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
}
65
66
private void createButton()
67
{
68
button = new JButton("Add Interest");
69
70
ActionListener listener = new AddInterestListener();
71
button.addActionListener(listener);
72
}
73
74
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
}
Copyright
© 2014 by John Wiley & Sons. All rights reserved.
84}
Page 50
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
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
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
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);
 Note that the button group does not place the buttons
close to each other on the container
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 53
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:
JPanel panel = new JPanel();
panel.add(smallButton);
panel.add(mediumButton);
panel.add(largeButton);
panel.setBorder(new
EtchedBorder(),"Size"));
 There are a large TitledBorder(new
number of border styles
available
• See the Swing documentation for more details
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 54
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
JRadioButton largeButton = new JRadioButton("Large");
largeButton.setSelected(true);

Call the isSelected method of each button to
find out which one it is currently selected
if (largeButton.isSelected())
{ size = LARGE_SIZE; }
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 55
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
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
Selecting Check Boxes

To setup a Check Box, use Swing JCheckBox
 Pass the constructor the name for the check box label
JCheckBox italicCheckBox = new JCheckBox("Italic");

Call the isSelected method of a checkbox to find
out whether it is currently selected or not
if (italicCheckBox.isSelected())
{ style = style + Font.ITALIC }
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 58
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
facenameCombo.setEditable();
 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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 59
Adding and Selecting Items

Add text ‘items’ to a combo box that will show in
the list:
JComboBox facenameCombo = new JComboBox();
facenameCombo.addItem("Serif");
facenameCombo.addItem("SansSerif");
. . .

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:
String selectedString = (String) facenameCombo.getSelectedItem();
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 60
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.
Serif, SansSerif, Monospaced
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 61
1.
2.
Create constants: frame width and frame height
Create variables:
1.
2.
3.
4.
5.
3.
Define no argument constructor
1.
2.
3.
4.
5.
4.
Label to display font “Big Java”
2 Checkboxes : italics, bold
3 Radiobuttons: small, medium, large
Combobox for font face name (Serif, SansSerif, Monospaced)
ActionListener to change display text based on user selections
Construct label with text “Big Java”
Add label to BorderLayout.CENTER
createControlPanel() : create checkboxes, radiobuttons, comboboxes add it to
BorderLayout.SOUTH.
Set label font
Set size
Implement nested class ChoiceListener that implements ActionListener
1.
Actionperformed method will set the label font to current user choices
Download template
Page 62

Test FontFrame class using following Tester
class:
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 63
Answer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
FontFrame.java
java.awt.BorderLayout;
java.awt.Font;
java.awt.GridLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
javax.swing.ButtonGroup;
javax.swing.JButton;
javax.swing.JCheckBox;
javax.swing.JComboBox;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;
javax.swing.JRadioButton;
javax.swing.border.EtchedBorder;
javax.swing.border.TitledBorder;
/**
This frame contains a text sample and a control panel
to change the font of the text.
*/
public class FontFrame extends JFrame
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 400;
private
private
private
private
private
private
private
private
JLabel label;
JCheckBox italicCheckBox;
JCheckBox boldCheckBox;
JRadioButton smallButton;
JRadioButton mediumButton;
JRadioButton largeButton;
JComboBox facenameCombo;
ActionListener listener;
Continued 
Page 64
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
Constructs the frame.
*/
public FontFrame()
{
// Construct text sample
label = new JLabel("Big Java");
add(label, BorderLayout.CENTER);
// This listener is shared among all components
listener = new ChoiceListener();
createControlPanel();
setLabelFont();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
class ChoiceListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
setLabelFont();
}
}
Continued 
Page 65
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
Creates the control panel to change the font.
*/
public void createControlPanel()
{
JPanel facenamePanel = createComboBox();
JPanel sizeGroupPanel = createCheckBoxes();
JPanel styleGroupPanel = createRadioButtons();
// Line up component panels
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new GridLayout(3, 1));
controlPanel.add(facenamePanel);
controlPanel.add(sizeGroupPanel);
controlPanel.add(styleGroupPanel);
// Add panels to content pane
add(controlPanel, BorderLayout.SOUTH);
}
/**
Creates the combo box with the font style choices.
@return the panel containing the combo box
*/
public JPanel createComboBox()
{
facenameCombo = new JComboBox();
facenameCombo.addItem("Serif");
facenameCombo.addItem("SansSerif");
facenameCombo.addItem("Monospaced");
facenameCombo.setEditable(true);
facenameCombo.addActionListener(listener);
JPanel panel = new JPanel();
panel.add(facenameCombo);
return panel;
}
Continued 
Page 66
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/**
Creates the check boxes for selecting bold and italic styles.
@return the panel containing the check boxes
*/
public JPanel createCheckBoxes()
{
italicCheckBox = new JCheckBox("Italic");
italicCheckBox.addActionListener(listener);
boldCheckBox = new JCheckBox("Bold");
boldCheckBox.addActionListener(listener);
JPanel panel = new JPanel();
panel.add(italicCheckBox);
panel.add(boldCheckBox);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Style"));
return panel;
}
Continued 
Page 67
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/**
Creates the radio buttons to select the font size.
@return the panel containing the radio buttons
*/
public JPanel createRadioButtons()
{
smallButton = new JRadioButton("Small");
smallButton.addActionListener(listener);
mediumButton = new JRadioButton("Medium");
mediumButton.addActionListener(listener);
largeButton = new JRadioButton("Large");
largeButton.addActionListener(listener);
largeButton.setSelected(true);
// Add radio buttons to button group
ButtonGroup group = new ButtonGroup();
group.add(smallButton);
group.add(mediumButton);
group.add(largeButton);
JPanel panel = new JPanel();
panel.add(smallButton);
panel.add(mediumButton);
panel.add(largeButton);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Size"));
Continued 
return panel;
}
Page 68
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190 }
/**
Gets user choice for font name, style, and size
and sets the font of the text sample.
*/
public void setLabelFont()
{
// Get font name
String facename = (String) facenameCombo.getSelectedItem();
// Get font style
int style = 0;
if (italicCheckBox.isSelected())
{
style = style + Font.ITALIC;
}
if (boldCheckBox.isSelected())
{
style = style + Font.BOLD;
}
// Get font size
int size = 0;
final int SMALL_SIZE = 24;
final int MEDIUM_SIZE = 36;
final int LARGE_SIZE = 48;
if (smallButton.isSelected()) { size = SMALL_SIZE; }
else if (mediumButton.isSelected()) { size = MEDIUM_SIZE; }
else if (largeButton.isSelected()) { size = LARGE_SIZE; }
// Set font of text field
label.setFont(new Font(facename, style, size));
label.repaint();
}
Page 69
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
Steps to Design a User Interface
2) 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
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
Steps to Design a User Interface
5) 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 default
pricePanel.add(new JLabel("Your Price:"));
pricePanel.add(priceTextField);
JPanel centerPanel = new JPanel(); // Uses FlowLayout
centerPanel.add(radioButtonPanel);
centerPanel.add(checkBoxPanel); // Frame uses BorderLayout by default
add(centerPanel, BorderLayout.CENTER);
add(pricePanel, BorderLayout.SOUTH);
Page 73
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);
Instantiate a menu bar, then add it to the
. . .
frame with the setJMenuBar method.
}
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 74
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
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu fontMenu = new JMenu("Font");
menuBar.add(fileMenu);
menuBar.add(fontMenu);
 A Menu contains SubMenus and Menu items
• A Menu item has no further SubMenus
• You add Menu items and SubMenus with the add method
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 75
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
Menu Item Events
 Add action listeners to each Menu item
ActionListener listener = new ExitItemListener();
exitItem.addActionListener(listener);
 The listener is customized for each Menu item
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 77
FaceEvent ActionListener (2)

Listener Inner Class version
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 78
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import
import
import
import
import
import
import
import
import
java.awt.BorderLayout;
java.awt.Font;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JMenu;
javax.swing.JMenuBar;
javax.swing.JMenuItem;
/**
This frame has a menu with commands to change the font
of a text sample.
*/
public class FontFrame2 extends JFrame
{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 400;
private
private
private
private
JLabel label;
String facename;
int fontstyle;
int fontsize;
/**
Constructs the frame.
*/
Continued 
Page 79
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public FontFrame2()
{
// Construct text sample
label = new JLabel("Big Java");
add(label, BorderLayout.CENTER);
// Construct menu
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
menuBar.add(createFileMenu());
menuBar.add(createFontMenu());
facename = "Serif";
fontsize = 24;
fontstyle = Font.PLAIN;
setLabelFont();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
class ExitItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
}
Continued 
Page 80
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
Creates the File menu.
@return the menu
*/
public JMenu createFileMenu()
{
JMenu menu = new JMenu("File");
JMenuItem exitItem = new JMenuItem("Exit");
ActionListener listener = new ExitItemListener();
exitItem.addActionListener(listener);
menu.add(exitItem);
return menu;
}
/**
Creates the Font submenu.
@return the menu
*/
public JMenu createFontMenu()
{
JMenu menu = new JMenu("Font");
menu.add(createFaceMenu());
menu.add(createSizeMenu());
menu.add(createStyleMenu());
return menu;
}
/**
Creates the Face submenu.
@return the menu
*/
public JMenu createFaceMenu()
{
JMenu menu = new JMenu("Face");
menu.add(createFaceItem("Serif"));
menu.add(createFaceItem("SansSerif"));
menu.add(createFaceItem("Monospaced"));
return menu;
}
Continued 
Page 81
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
120
121
122
/**
Creates the Size submenu.
@return the menu
*/
public JMenu createSizeMenu()
{
JMenu menu = new JMenu("Size");
menu.add(createSizeItem("Smaller", -1));
menu.add(createSizeItem("Larger", 1));
return menu;
}
/**
Creates the Style submenu.
@return the menu
*/
public JMenu createStyleMenu()
{
JMenu menu = new JMenu("Style");
menu.add(createStyleItem("Plain", Font.PLAIN));
menu.add(createStyleItem("Bold", Font.BOLD));
menu.add(createStyleItem("Italic", Font.ITALIC));
menu.add(createStyleItem("Bold Italic", Font.BOLD+ Font.ITALIC));
return menu;
}
Continued 
Page 82
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/**
Creates a menu item to change the font face and set its action listener.
@param name the name of the font face
@return the menu item
*/
public JMenuItem createFaceItem(final String name)
{
class FaceItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
facename = name;
setLabelFont();
}
}
JMenuItem item = new JMenuItem(name);
ActionListener listener = new FaceItemListener();
item.addActionListener(listener);
return item;
}
Continued 
Page 83
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/**
Creates a menu item to change the font size
and set its action listener.
@param name the name of the menu item
@param increment the amount by which to change the size
@return the menu item
*/
public JMenuItem createSizeItem(String name, final int increment)
{
class SizeItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
fontsize = fontsize + increment;
setLabelFont();
}
}
JMenuItem item = new JMenuItem(name);
ActionListener listener = new SizeItemListener();
item.addActionListener(listener);
return item;
}
Continued 
Page 84
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201}
/**
Creates a menu item to change the font style
and set its action listener.
@param name the name of the menu item
@param style the new font style
@return the menu item
*/
public JMenuItem createStyleItem(String name, final int style)
{
class StyleItemListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
fontstyle = style;
setLabelFont();
}
}
JMenuItem item = new JMenuItem(name);
ActionListener listener = new StyleItemListener();
item.addActionListener(listener);
return item;
}
/**
Sets the font of the text sample.
*/
public void setLabelFont()
{
Font f = new Font(facename, fontstyle, fontsize);
label.setFont(f);
}
Try it: ch19/section_4
Page 85
JDesktopPane and JInternalFrame

Allow you to display child windows inside main/parent windows

Create Desktop pane inside JFrame:
JDesktopPane theDesktop;
theDesktop = new JDesktopPane();
add( theDesktop ); // add desktop pane to JFrame

Create an internal frame:
JInternalFrame internalFrame = new JInternalFrame("Internal
Frame", true, true, true, true );
or define a class that extend JInternalFrame and then:
JInternalFrame internalFrame = new LoginInternalFrame();

Add internal frame to Desktop pane:
theDesktop.add( internalFrame ); // attach internal frame
Page 86
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 87
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
Answer
1 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;
16
17public class MainMenuFrame extends JFrame
18{
19
private JDesktopPane theDesktop;
20
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Continued 
Page 89
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// set up GUI
public MainMenuFrame()
{
super( "Using a JDesktopPane" );
JMenuBar bar = new JMenuBar(); // create menu bar
JMenu addMenu = new JMenu( "File" ); // create Add menu
JMenuItem accessMenuItem = new JMenuItem( "AcessInternalFrame" );
addMenu.add( accessMenuItem ); // 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 ); // add desktop pane to frame
Continued 
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 90
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// set up listener for newFrame menu item
accessMenuItem.addActionListener(
new ActionListener() // anonymous inner class
{
// display new internal window
public void actionPerformed( ActionEvent event )
{
// create internal frame
JInternalFrame internalFrame = new JInternalFrame("Internal Frame", true, true, true, true );
internalFrame.setTitle("Sample Internal Frame");
internalFrame.setSize(500, 500);
internalFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
JPanel p = new JPanel();
p.add(new JLabel("sample text"));
internalFrame.getContentPane().add(p);
internalFrame.add( p, BorderLayout.CENTER ); // add panel
internalFrame.pack(); // set internal frame to size of contents
theDesktop.add( internalFrame ); // attach internal frame
internalFrame.setVisible( true ); // show internal frame
}
}
);
}
Continued 
Page 91
65
66
67
68
69
70
71
72}
public static void main( String[] args )
{
MainMenuFrame mainMenuFrame = new MainMenuFrame();
mainMenuFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
mainMenuFrame.setSize( 600, 480 ); // set frame size
mainMenuFrame.setVisible( true ); // display frame
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 92
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
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
Answer
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
MainMenuFrame2.java
java.awt.BorderLayout;
java.awt.Dimension;
java.awt.Graphics;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
java.util.Random;
javax.swing.JFrame;
javax.swing.JDesktopPane;
javax.swing.JMenuBar;
javax.swing.JMenu;
javax.swing.JMenuItem;
javax.swing.JInternalFrame;
javax.swing.JPanel;
javax.swing.JLabel;
javax.swing.ImageIcon;
public class MainMenuFrame2 extends JFrame
{
private JDesktopPane theDesktop;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Continued 
Page 95
// 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
}
}
);
}
Continued 
Page 96
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
LoginInternalFrame.java
import
import
import
import
import
import
import
import
import
import
import
import
import
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JButton;
javax.swing.JTextField;
javax.swing.JPasswordField;
javax.swing.JOptionPane;
javax.swing.JInternalFrame;
java.util.Scanner;
java.awt.GridLayout;
java.io.File;
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;
Continued 
Page 98
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 99
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 100
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 101

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
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
ListFrame.java
// ListFrame.java
import 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 };
Continued 
Page 104
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
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
JTabbedPaneFrame.java
import
import
import
import
import
import
import
import
java.awt.BorderLayout;
java.awt.Color;
javax.swing.JFrame;
javax.swing.JTabbedPane;
javax.swing.JLabel;
javax.swing.JPanel;
javax.swing.JButton;
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" );
Continued 
Page 107
// 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
JTabbedPaneDemo.java
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Page 109

Find out more:
 BoxLayout
 GridBagLayout
 Jpopup menus
Page 110