Java Programming Chapter 10 Graphical User Interfaces
Objectives In this chapter you will: Explore various types of user interfaces Develop a graphical user interface (GUI) Learn how the GUI classes in Java are organized and related Add functionality to a GUI with event- driven programming Improve a GUI’s layout
Creating User Interfaces So far we have created console user interfaces and simple GUIs In this chapter we will compare these user interfaces with more developed and functional GUIs We will learn how to create advanced GUIs
A Console User Interface 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 1970s
A Console User Interface (continued)
A Simple GUI Similar to the GUIs used so far in the book A series of windows collects the required information Program code is shorter and simpler than the console UI Functionality is more or less the same
A Simple GUI (continued)
A More Complete GUI The program produces one window which contains all the user information Simpler for the user Requires much more programming
A More Complete GUI (continued)
Overview of a Java GUI GUI components: Swing vs. AWT A GUI class hierarchy The Component class and layout manager classes Containers of components Components within components
GUI Components: Swing vs. AWT 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 Java classes that create GUI components are part of the javax.swing package They 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 The appearance of Swing components is platform independent AWT components require the resources of the operating system, so they are heavyweight components Swing components require only the Java runtime system, so they are lightweight components
A GUI Class Hierarchy Recall that inheritance in Java means that subclasses have direct access to nonprivate members of superclasses Objects created from subclasses have full access to nonprivate superclass members This eliminates redundant code and promotes reuse
A GUI Class Hierarchy (continued)
The Component Class and Layout Manager Classes 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 Component class is abstract A concrete class is a class from which objects can be created
The Component Class and Layout Manager Classes (continued) A Container object contains other components add 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 getContentPane returns a window that fits within a JFrame and holds other components
The Component Class and Layout Manager Classes The class JComponent is an abstract base class for all Swing components except JFrame Contains fields and methods placed in a window JComponent subdivides into abstract classes JTextComponent and AbstractButton Lower level concrete classes JTextField, JButton, Jlabel, and JPanel create actual component objects
Developing a Java GUI Step-by-step development of a GUI using AWT and Swing packages The JFrame class The JLabel class The JTextField class The JButton class
The JFrame Class Produces a simple frame with no contents Inherits the nonprivate members of JFrame public class BankAppGuiOne extends JFrame Constructor specifies how to create the GUI Recall program execution starts with main A JFrame object is created by calling the constructor JFrame aBankAppGuiOne = new BankAppGuiOne();
The JFrame Class (continued)
The JLabel Class 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 are displayed in the order they are added The main method creates the JFrame object, sets the window’s closing method, and makes the GUI visible
The JLabel Class (continued)
The JTextField Class A JTextField allows a single line of text to be edited Inherits from JTextComponent getText obtains the text from the field setText displays text in the field The JTextField objects are added to the content pane, each following its label The components are added to the grid left to right, top to bottom
The JTextField Class (continued)
The JButton Class A button is a component the user clicks to trigger an event, such as calling a method in a program Command buttons, check boxes, option buttons Inherits from AbstractButton, which contains the method setEnabled Activates 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 Design the appearance of the GUI using a mockup
Apply the Concept (continued)
The main method calls the calculator’s constructor to create the JFrame object 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
Apply the Concept (continued) The JFrame object is created by calling the CalculatorGuiOne constructor The constructor creates the GUI and calls centerFrame The Dimension class is used to capture the dimensions of the user’s screen The center of the user’s screen is calculated The method setBounds from the Window class positions the GUI
Apply the Concept (continued)
Adding Functionality to a GUI The banking GUI in Figure has no functionality The two buttons (Accept and Clear) do nothing when clicked The desired function is to write the customer information entered by the user to a file
Event-Driven Programming 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 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 The event object is created when an event occurs The event handler is an object that responds to a particular event When the event handler detects an event object, it calls the event handler method The programmer registers the handler with the event object by associating them with program code
Event-Driven Programming (continued)
How to Implement Event Handling 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 ActionListener interface ActionListener has only the method actionPerformed The functionality of the component is defined within the method actionPerformed
How to Implement Event Handling (continued) Create the event handler object from the class private AcceptButtonHandler abHandler; abHandler = new AcceptButtonHandler(); Register the event handler object with an event object (in this case the button acceptB ) acceptB.addActionListener (abHandler); The method addActionListener enables abHandler to listen for the user to click acceptB When acceptB is clicked, the actionPerformed method is called
Apply the Concept Continue to develop the calculator by adding functionality Require four inner classes for the arithmetic buttons Each inner class implements the method actionPerformed, which executes the arithmetic operation and displays the answer The getText method of JTextField gets the user input and stores it in strings An if structure prevents division by zero
Improving GUI Layout 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 NetBeans and JFrameBuilder provide graphical tools to design complex GUIs The next section focuses on building GUIs directly from program code
The JPanel Class The JPanel class creates panels that hold GUI components JPanel labelPanel = new JPanel(); The panels can have a layout assigned such as a grid or a flow Layouts organize how components are displayed within the panel
The FlowLayout Class The FlowLayout class arranges components within a container’s directional flow Left to right is the default Can also flow right to left Components are arranged in a continuous flow in the order they were added within the container’s fixed width Example: A FlowLayout object, right-aligned FlowLayout fR = new FlowLayout(FlowLayout.RIGHT);
The BorderLayout Class 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 BorderLayout Class (continued)
BankAppGuiFive.java is improved with BorderLayout for the GUI SwingConstants is an interface that contains only constants such as RIGHT and TOP Create GridLayout for the data and FlowLayout for the buttons Add the panels to NORTH and SOUTH regions in BorderLayout
The BorderLayout Class (continued)
Case Study: MusicWorld Read CD data from a file and write sales transaction data to file Improve by using an all-in-one GUI 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 MusicWorldApp10.java
Program Code for MusicWorldApp10.java 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 MusicWorldApp10 to make them accessible to inner classes The constructor creates the GUI The methods setEnabled and setEditable activate and deactivate components
Program Code for MusicWorldApp10.java Most processing is done by the inner classes The inner classes use mostly code from MusicWorldApp9.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 actionPerformed method generates output
Program Code for MusicWorldApp10.java When the New button is clicked, the inner class resets the arrays, variables, and GUI components to their original state The Exit Button Handler exits the application The main Method Calls the constructor to MusicWorldApp10 Sets the function of the close button Makes the GUI visible to the user
Summary 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) The Container class creates a container to fit inside a frame and holds components of a GUI The JLabel, JTextField, 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