Java Programming Chapter 10 Graphical User Interfaces Objectives

Java Programming Chapter 10 Graphical User Interfaces

Objectives In this chapter you will: n Explore various types of user interfaces n Develop a graphical user interface (GUI) n Learn how the GUI classes in Java are organized and related n Add functionality to a GUI with eventdriven programming n Improve a GUI’s layout

Creating User Interfaces So far we have created console user interfaces and simple GUIs n In this chapter we will compare these user interfaces with more developed and functional GUIs n We will learn how to create advanced GUIs n

A Console User Interface n n n The Scanner class is instantiated using System. in, which takes input from the keyboard A text prompt is printed to the screen asking for information from the user The Scanner object collects the user input The input is processed This type of UI is typical of UIs in the 1970 s

A Console User Interface (continued)

A Simple GUI Similar to the GUIs used so far in the book n A series of windows collects the required information n Program code is shorter and simpler than the console UI n Functionality is more or less the same n

A Simple GUI (continued)

A Simple GUI (continued)

A More Complete GUI The program produces one window which contains all the user information n Simpler for the user n Requires much more programming n

A More Complete GUI (continued)

Overview of a Java GUI components: Swing vs. AWT n A GUI class hierarchy n The Component class and layout manager classes n ¨ Containers of components ¨ Components within components

GUI Components: Swing vs. AWT n A Java GUI consists of a window that contains components with which the user interacts ¨ Components are objects such as buttons, labels, or text fields n Java classes that create GUI components are part of the javax. swing package ¨ They n are called Swing components Earlier versions of Java used the Abstract Windowing Toolkit (AWT) ¨ Classes in the package java. awt

GUI Components: Swing vs. AWT (continued) The appearance of GUIs created with the AWT depends on the platform n The appearance of Swing components is platform independent n AWT components require the resources of the operating system, so they are heavyweight components n Swing components require only the Java runtime system, so they are lightweight components n

A GUI Class Hierarchy Recall that inheritance in Java means that subclasses have direct access to nonprivate members of superclasses n Objects created from subclasses have full access to nonprivate superclass members n This eliminates redundant code and promotes reuse n

A GUI Class Hierarchy (continued)

The Component Class and Layout Manager Classes n n Creating GUIs involves a combination of Swing classes and AWT classes All Java classes inherit from the Object class A layout manager controls how components are arranged in a GUI window An abstract class contains variables and methods but no objects can be created from it ¨ The n Component class is abstract A concrete class is a class from which objects can be created

The Component Class and Layout Manager Classes (continued) n A Container object contains other components ¨ add n n n in the Container class adds components The class Window creates a window without a border or menu bar The class Frame creates a window with a border and title bar The class JFrame is similar to Frame ¨ Supports other lightweight components ¨ get. Content. Pane returns a window that fits within a JFrame and holds other components

The Component Class and Layout Manager Classes n The class JComponent is an abstract base class for all Swing components except JFrame ¨ Contains n n fields and methods placed in a window JComponent subdivides into abstract classes JText. Component and Abstract. Button Lower level concrete classes JText. Field, JButton, Jlabel, and JPanel create actual component objects

Developing a Java GUI Step-by-step development of a GUI using AWT and Swing packages n The JFrame class n The JLabel class n The JText. Field class n The JButton class n

The JFrame Class n n Produces a simple frame with no contents Inherits the nonprivate members of JFrame public class Bank. App. Gui. One extends JFrame n n n Constructor specifies how to create the GUI Recall program execution starts with main A JFrame object is created by calling the constructor JFrame a. Bank. App. Gui. One = new Bank. App. Gui. One();

The JFrame Class (continued)

The JLabel Class n n n A JLabel object displays a single line of text The Container object is formatted so that components are in a grid JLabel objects are created and added to the Container object ¨ Components added n are displayed in the order they are The main method creates the JFrame object, sets the window’s closing method, and makes the GUI visible

The JLabel Class (continued)

The JText. Field Class A JText. Field allows a single line of text to be edited n Inherits from JText. Component n obtains the text from the field ¨ set. Text displays text in the field ¨ get. Text The JText. Field objects are added to the content pane, each following its label n The components are added to the grid left to right, top to bottom n

The JText. Field Class (continued)

The JButton Class n A button is a component the user clicks to trigger an event, such as calling a method in a program ¨ Command n Inherits from Abstract. Button, which contains the method set. Enabled ¨ Activates n n buttons, check boxes, option buttons and deactivates buttons as desired The grid is adjusted to have 5 rows instead of 4 The JButton objects are created and added to the content pane

The JButton Class (continued)

Apply the Concept Create a simple calculator using buttons and text fields n Design the appearance of the GUI using a mockup n

Apply the Concept (continued)

Apply the Concept (continued) n The main method calls the calculator’s constructor to create the JFrame object n In the constructor, the GUI’s title and size are determined, and a content pane is created The content pane has a grid layout with 5 rows and 2 columns Labels, text fields, and buttons are created and added to the content pane The frame is centered on the user’s screen n

Apply the Concept (continued) The JFrame object is created by calling the Calculator. Gui. One constructor n The constructor creates the GUI and calls center. Frame n The Dimension class is used to capture the dimensions of the user’s screen n The center of the user’s screen is calculated n The method set. Bounds from the Window class positions the GUI n

Apply the Concept (continued)

Adding Functionality to a GUI The banking GUI in Figure 10. 14 has no functionality n The two buttons (Accept and Clear) do nothing when clicked n The desired function is to write the customer information entered by the user to a file n

Event-Driven Programming n n The process of writing programs in which sections of code are executed by events An event is a change in state of a GUI component resulting from a user action ¨ For n n example, a button being clicked or a key stroke When the event happens, the application creates an event object and initiates functionality Event-handling mechanisms have three parts ¨ Event source, event object and event handler

Event-Driven Programming (continued) The event source is the GUI component n The event object is created when an event occurs n The event handler is an object that responds to a particular event n When the event handler detects an event object, it calls the event handler method n The programmer registers the handler with the event object by associating them with program code n

Event-Driven Programming (continued)

How to Implement Event Handling n n Event handling is implemented in three steps Create an inner class to handle a specific event The class should be private and nonstatic The class should implement the Action. Listener interface ¨ n Action. Listener has only the method action. Performed The functionality of the component is defined within the method action. Performed

How to Implement Event Handling (continued) n n Create the event handler object from the class private Accept. Button. Handler ab. Handler; ab. Handler = new Accept. Button. Handler(); Register the event handler object with an event object (in this case the button accept. B) accept. B. add. Action. Listener (ab. Handler); The method add. Action. Listener enables ab. Handler to listen for the user to click accept. B When accept. B is clicked, the action. Performed method is called

Apply the Concept n n n Continue to develop the calculator by adding functionality Require four inner classes for the arithmetic buttons Each inner class implements the method action. Performed, which executes the arithmetic operation and displays the answer The get. Text method of JText. Field gets the user input and stores it in strings An if structure prevents division by zero

Improving GUI Layout n n More complex applications require more versatile GUIs The Java AWT provides tools for controlling a GUI’s layout Java Integrated Development Environment (IDE) such as Net. Beans and JFrame. Builder provide graphical tools to design complex GUIs The next section focuses on building GUIs directly from program code

The JPanel Class n The JPanel class creates panels that hold GUI components JPanel label. Panel = new JPanel(); The panels can have a layout assigned such as a grid or a flow n Layouts organize how components are displayed within the panel n

The Flow. Layout Class n The Flow. Layout class arranges components within a container’s directional flow ¨ Left to right is the default ¨ Can also flow right to left n n Components are arranged in a continuous flow in the order they were added within the container’s fixed width Example: A Flow. Layout object, right-aligned Flow. Layout f. R = new Flow. Layout(Flow. Layout. RIGHT);

The Border. Layout Class n n n Arranges components into regions of the content pane: NORTH, SOUTH, EAST, WEST, CENTER Each region expands to hold its contents, constrained by container’s size and frame size The NORTH and SOUTH components stretch horizontally The EAST and WEST components stretch vertically The CENTER component stretches both ways

The Border. Layout Class (continued)

The Border. Layout Class (continued) Bank. App. Gui. Five. java is improved with Border. Layout for the GUI n Swing. Constants is an interface that contains only constants such as RIGHT and TOP n Create Grid. Layout for the data and Flow. Layout for the buttons n Add the panels to NORTH and SOUTH regions in Border. Layout n

The Border. Layout Class (continued)

Case Study: Music. World n n n Read CD data from a file and write sales transaction data to file Improve by using an all-in-one GUI should allow the user to enter information about the number of CDs, the CD ID, and quantity Display the item with information such as subtotal and total Allow the user to manipulate the order display

Flowcharts for New Features of Music. World. App 10. java

Program Code for Music. World. App 10. java n n n Complete code rewrite, with some reuse, and an increase in length of 60% The class declaration extends JFrame Variables and methods are declared in the class Music. World. App 10 to make them accessible to inner classes The constructor creates the GUI The methods set. Enabled and set. Editable activate and deactivate components

Program Code for Music. World. App 10. java n Most processing is done by the inner classes n n The inner classes use mostly code from Music. World. App 9. java When the Confirm button is clicked, the arrays are loaded with item information When the View button is clicked, a for loop displays item information arrays When the Finish button is clicked, the action. Performed method generates output

Program Code for Music. World. App 10. java When the New button is clicked, the inner class resets the arrays, variables, and GUI components to their original state n The Exit Button Handler exits the application n The main Method n ¨ Calls the constructor to Music. World. App 10 ¨ Sets the function of the close button ¨ Makes the GUI visible to the user

Summary n n n A heavyweight component requires the resources of the operating system A lightweight component is a Swing component that requires only the Java runtime system A GUI is constructed with methods from the Swing and AWT packages An abstract class contains variables and methods, but no objects can be created from it The JFrame class creates the outer frame of a GUI

Summary (continued) n n n The Container class creates a container to fit inside a frame and holds components of a GUI The JLabel, JText. Field, and JButton classes create individual components of a GUI To make a GUI functional, the programmer must write an inner class to handle events An event object is created from the inner class The event handling object is registered with an event source object
- Slides: 53