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

Slides:



Advertisements
Similar presentations
Chapter 19 – Graphical User Interfaces
Advertisements

Graphical User Interfaces (Part IV)
Graphical User Interfaces, 2D Graphics & Game Programming.
Chapter Eighteen: Graphical User Interfaces. Chapter Goals To understand the use of layout managers to arrange user- interface components in a container.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
Java Programming Chapter 10 Graphical User Interfaces.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Combo Box, Check Boxes, and Radio Buttons. Radio Buttons User can click radio buttons, just like other buttons BUT Radio buttons are mutually exclusive.
Using Inheritance to Customize Frames Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
CSE 219 Computer Science III Graphical User Interface.
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
1 Why layout managers Can we perform layout without them? –Yes. A container’s layout property can be set to null. Absolute positioning: specify size and.
Chapter 12 Event Handling. Chapter Goals To understand the Java event model To install action and mouse event listeners To accept input from buttons,
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Chapter 14 Graphical User Interfaces. Chapter Goals To use inheritance to customize frames To understand how user-interface components are added to a.
Chapter 17 – Graphical User Interfaces Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Fall 2006Adapded from Java Concepts Companion Slides1 Event Handling Advanced Programming ICOM 4015 Lecture 13 Reading: Java Concepts Chapter 12.
Copyright © 2013 by John Wiley & Sons. All rights reserved. GRAPHICAL USER INTERFACES CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphical User Interface. Chapter Goals To understand the use of layout managers to arrange user- interface components in a container To become familiar.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine and Ten Graphics.
Fall 2006Adapted from Java Concepts Companion Slides1 Graphical User Interfaces Advanced Programming ICOM 4015 Lecture 12 Reading: Java Concepts Chapter.
Chapter 14 Graphical User Interfaces. Chapter Goals To use inheritance to customize frames To understand how user-interface components are added to a.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
CSE 501N Fall ‘09 18: Java GUI (Swing) 10 November 2009 Nick Leidenfrost.
Copyright © 2013 by John Wiley & Sons. All rights reserved. ADVANCED USER INTERFACES CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/2011.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display.
Basics of GUI Programming Chapter 11 and Chapter 22.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
GUI Components CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Computer Science [3] Java Programming II - Laboratory Course Lab 4 -1 : Introduction to Graphical user interface GUI Components Faculty of Engineering.
Chapter 14 Graphical User Interfaces. Chapter Goals To understand how to create frames To use inheritance to customize frames To understand how user-interface.
Java Programming Week 5: Graphical User Interfaces (Chapter 18)
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
Lecture # 6 Graphical User Interface(GUI). Introduction A graphical user interface (GUI) presents a user- friendly mechanism for interacting with an application.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Event Handling and GUI Components.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Event Handler Methods Text field Object Responder JAVA AWT Environment: Messages are sent between JAVA Objects Screen Event Notification Press Button.
Introduction to GUI in 1 Graphical User Interface 3 Nouf Almunyif.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Christopher Budo, Davis Nygren, spencer franks, Luke miller
A First Look at GUI Applications
A Quick Java Swing Tutorial
Chapter 13: Advanced GUIs and Graphics
Chapter 20 – Graphical User Interfaces
Chapter 14 Graphical User Interfaces
Chapter 12 Event Handling
Introduction to Event Handling
A Quick Java Swing Tutorial
Advanced Programming in Java
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

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 Page 6 The menus, buttons and combo box are part of the application’s GUI. They enable you to interact with the application.

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

Page 9 null = result in centering message in screen 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. 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 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

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: 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 }

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

 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); }

 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 !!! 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); }

 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 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

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

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

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); 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

 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); }

 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); panel.setLayout(new BorderLayout()); panel.add(component, BorderLayout.NORTH); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 25

 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); }

 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); }

 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  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);... buttonPanel.add(button7); buttonPanel.add(button8); buttonPanel.add(button9); buttonPanel.add(button4);... JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3)); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3)); Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 29

 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); }

 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 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); 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

 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); }

 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); 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  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()); 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. 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

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 template Page 38

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 **/ }

 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); }

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 JFrame 13{ 14 private static final int FRAME_WIDTH = 450; 15 private static final int FRAME_HEIGHT = 100; private static final double DEFAULT_RATE = 5; 18 private static final double INITIAL_BALANCE = 1000; private JLabel rateLabel; 21 private JTextField rateField; 22 private JButton button; 23 private JLabel resultLabel; 24 private double balance; public InvestmentFrame2() 27 { 28 balance = INITIAL_BALANCE; resultLabel = new JLabel("Balance: " + balance); createTextField(); 33 createButton(); 34 createPanel(); setSize(FRAME_WIDTH, FRAME_HEIGHT); 37 } 38 InvestmentFrame2.java Continued 

Copyright © 2014 by John Wiley & Sons. All rights reserved. Page private void createTextField() 40 { 41 rateLabel = new JLabel("Interest Rate: "); final int FIELD_WIDTH = 10; 44 rateField = new JTextField(FIELD_WIDTH); 45 rateField.setText("" + DEFAULT_RATE); 46 } /** 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 } private void createButton() 63 { 64 button = new JButton("Add Interest"); ActionListener listener = new AddInterestListener(); 67 button.addActionListener(listener); 68 } 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 }

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); 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

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);

JTextField and JTextArea  J TextField 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 Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 46  To add scroll bars, use J ScrollPane: JScrollPane scrollPane = new JScrollPane(textArea);

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); }

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; 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; private static final int AREA_ROWS = 10; 21 private static final int AREA_COLUMNS = 30; private static final double DEFAULT_RATE = 5; 24 private static final double INITIAL_BALANCE = 1000; private JLabel rateLabel; 27 private JTextField rateField; 28 private JButton button; 29 private JTextArea resultArea; 30 private double balance; 31 Continued  InvestmentFrame3.java

Copyright © 2014 by John Wiley & Sons. All rights reserved. Page public InvestmentFrame3() 33 { 34 balance = INITIAL_BALANCE; 35 resultArea = new JTextArea(AREA_ROWS, AREA_COLUMNS); 36 resultArea.setText(balance + "\n"); 37 resultArea.setEditable(false); createTextField(); 40 createButton(); 41 createPanel(); setSize(FRAME_WIDTH, FRAME_HEIGHT); 44 } private void createTextField() 47 { 48 rateLabel = new JLabel("Interest Rate: "); final int FIELD_WIDTH = 10; 51 rateField = new JTextField(FIELD_WIDTH); 52 rateField.setText("" + DEFAULT_RATE); 53 } 54 Continued 

Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 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 } private void createButton() 67 { 68 button = new JButton("Add Interest"); ActionListener listener = new AddInterestListener(); 71 button.addActionListener(listener); 72 } 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}

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 JRadioButton s 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); 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

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")); 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

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); JRadioButton largeButton = new JRadioButton("Large"); largeButton.setSelected(true); if (largeButton.isSelected()) { size = LARGE_SIZE; } 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  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 } 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  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

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");... 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

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

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 constructor 1.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 ActionListener 1.Actionperformed method will set the label font to current user choices Download template Page 62

 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); }

Answer 1 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; /** 18 This frame contains a text sample and a control panel 19 to change the font of the text. 20 */ 21 public class FontFrame extends JFrame 22 { 23 private static final int FRAME_WIDTH = 300; 24 private static final int FRAME_HEIGHT = 400; 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 /** 36 Constructs the frame. 37 */ 38 public FontFrame() 39 { 40 // Construct text sample 41 label = new JLabel("Big Java"); 42 add(label, BorderLayout.CENTER); // This listener is shared among all components 45 listener = new ChoiceListener(); createControlPanel(); 48 setLabelFont(); 49 setSize(FRAME_WIDTH, FRAME_HEIGHT); 50 } class ChoiceListener implements ActionListener 53 { 54 public void actionPerformed(ActionEvent event) 55 { 56 setLabelFont(); 57 } 58 } 59 Continued 

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(); // Line up component panels JPanel controlPanel = new JPanel(); 72 controlPanel.setLayout(new GridLayout(3, 1)); 73 controlPanel.add(facenamePanel); 74 controlPanel.add(sizeGroupPanel); 75 controlPanel.add(styleGroupPanel); // Add panels to content pane add(controlPanel, BorderLayout.SOUTH); 80 } /** 83 Creates the combo box with the font style choices. the panel containing the combo box 85 */ 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); JPanel panel = new JPanel(); 96 panel.add(facenameCombo); 97 return panel; 98 } Page 66 Continued 

/** 101 Creates the check boxes for selecting bold and italic styles. the panel containing the check boxes 103 */ 104 public JPanel createCheckBoxes() 105 { 106 italicCheckBox = new JCheckBox("Italic"); 107 italicCheckBox.addActionListener(listener); boldCheckBox = new JCheckBox("Bold"); 110 boldCheckBox.addActionListener(listener); JPanel panel = new JPanel(); 113 panel.add(italicCheckBox); 114 panel.add(boldCheckBox); 115 panel.setBorder(new TitledBorder(new EtchedBorder(), "Style")); return panel; 118 } 119 Page 67 Continued 

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

/** 153 Gets user choice for font name, style, and size 154 and sets the font of the text sample. 155 */ 156 public void setLabelFont() 157 { 158 // Get font name 159 String facename = (String) facenameCombo.getSelectedItem(); // Get font style 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 } // Get font size int size = 0; final int SMALL_SIZE = 24; 178 final int MEDIUM_SIZE = 36; 179 final int LARGE_SIZE = 48; if (smallButton.isSelected()) { size = SMALL_SIZE; } 182 else if (mediumButton.isSelected()) { size = MEDIUM_SIZE; } 183 else if (largeButton.isSelected()) { size = LARGE_SIZE; } // Set font of text field label.setFont(new Font(facename, style, size)); 188 label.repaint(); 189 } 190 } 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); 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);... }... } 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.

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); 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

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  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); ActionListener listener = new ExitItemListener(); exitItem.addActionListener(listener);

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; } 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; }

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; /** 12 This frame has a menu with commands to change the font 13 of a text sample. 14 */ 15 public class FontFrame2 extends JFrame 16 { 17 private static final int FRAME_WIDTH = 300; 18 private static final int FRAME_HEIGHT = 400; private JLabel label; 21 private String facename; 22 private int fontstyle; 23 private int fontsize; /** 26 Constructs the frame. 27 */ Page 79 Continued 

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

56 /** 57 Creates the File menu. the menu 59 */ 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 } /** 71 Creates the Font submenu. the menu 73 */ 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 } /** 84 Creates the Face submenu. the menu 86 */ 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 

95 96 /** 97 Creates the Size submenu. the menu 99 */ 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 } /** 109 Creates the Style submenu. the menu 111 */ 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 

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

145 /** 146 Creates a menu item to change the font size 147 and set its action listener. name the name of the menu item increment the amount by which to change the size the menu item 151 */ 152 public JMenuItem createSizeItem(String name, final int increment) 153 { 154 class SizeItemListener implements ActionListener 155 { 156 public void actionPerformed(ActionEvent event) 157 { 158 fontsize = fontsize + increment; 159 setLabelFont(); 160 } 161 } JMenuItem item = new JMenuItem(name); 164 ActionListener listener = new SizeItemListener(); 165 item.addActionListener(listener); 166 return item; 167 } Page 84 Continued 

/** 170 Creates a menu item to change the font style 171 and set its action listener. name the name of the menu item style the new font style the menu item 175 */ 176 public JMenuItem createStyleItem(String name, final int style) 177 { 178 class StyleItemListener implements ActionListener 179 { 180 public void actionPerformed(ActionEvent event) 181 { 182 fontstyle = style; 183 setLabelFont(); 184 } 185 } JMenuItem item = new JMenuItem(name); 188 ActionListener listener = new StyleItemListener(); 189 item.addActionListener(listener); 190 return item; 191 } /** 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

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

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. Page 89 Continued 

21 // set up GUI 22 public MainMenuFrame() 23 { 24 super( "Using a JDesktopPane" ); JMenuBar bar = new JMenuBar(); // create menu bar 27 JMenu addMenu = new JMenu( "File" ); // create Add menu 28 JMenuItem accessMenuItem = new JMenuItem( "AcessInternalFrame" ); addMenu.add( accessMenuItem ); // add new frame item to Add menu 31 bar.add( addMenu ); // add Add menu to menu bar 32 setJMenuBar( bar ); // set menu bar for this application theDesktop = new JDesktopPane(); // create desktop pane 35 add( theDesktop ); // add desktop pane to frame 36 Copyright © 2014 by John Wiley & Sons. All rights reserved. Page 90 Continued 

37 // set up listener for newFrame menu item 38 accessMenuItem.addActionListener( new ActionListener() // anonymous inner class 41 { 42 // display new internal window 43 public void actionPerformed( ActionEvent event ) 44 { 45 // create internal frame 46 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")); internalFrame.getContentPane().add(p); internalFrame.add( p, BorderLayout.CENTER ); // add panel 56 internalFrame.pack(); // set internal frame to size of contents theDesktop.add( internalFrame ); // attach internal frame 59 internalFrame.setVisible( true ); // show internal frame 60 } 61 } 62 ); 63 } 64 Page 91 Continued 

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 size 70 mainMenuFrame.setVisible( true ); // display frame 71 } 72} 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”logins.txt  Hint: Page 94

Answer import 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 

// 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 

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 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 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 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 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); }

 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 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 }; Page 104 ListFrame.java Continued 

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

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 

// 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

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

 Find out more:  BoxLayout  GridBagLayout  Jpopup menus Page 110