53
Java Programming Chapter 10 Graphical User Interfaces

Java Programming Chapter 10 Graphical User Interfaces

Embed Size (px)

Citation preview

  • Slide 1
  • Java Programming Chapter 10 Graphical User Interfaces
  • Slide 2
  • 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 GUIs layout
  • Slide 3
  • 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
  • Slide 4
  • 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
  • Slide 5
  • A Console User Interface (continued)
  • Slide 6
  • 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
  • Slide 7
  • A Simple GUI (continued)
  • Slide 8
  • Slide 9
  • A More Complete GUI The program produces one window which contains all the user information Simpler for the user Requires much more programming
  • Slide 10
  • A More Complete GUI (continued)
  • Slide 11
  • 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
  • Slide 12
  • 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
  • Slide 13
  • 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
  • Slide 14
  • 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
  • Slide 15
  • A GUI Class Hierarchy (continued)
  • Slide 16
  • 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
  • Slide 17
  • 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
  • Slide 18
  • 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
  • Slide 19
  • 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
  • Slide 20
  • 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();
  • Slide 21
  • The JFrame Class (continued)
  • Slide 22
  • 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 windows closing method, and makes the GUI visible
  • Slide 23
  • The JLabel Class (continued)
  • Slide 24
  • 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
  • Slide 25
  • The JTextField Class (continued)
  • Slide 26
  • 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
  • Slide 27
  • The JButton Class (continued)
  • Slide 28
  • Apply the Concept Create a simple calculator using buttons and text fields Design the appearance of the GUI using a mockup
  • Slide 29
  • Apply the Concept (continued)
  • Slide 30
  • The main method calls the calculators constructor to create the JFrame object In the constructor, the GUIs 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 users screen
  • Slide 31
  • 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 users screen The center of the users screen is calculated The method setBounds from the Window class positions the GUI
  • Slide 32
  • Apply the Concept (continued)
  • Slide 33
  • Adding Functionality to a GUI The banking GUI in Figure 10.14 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
  • Slide 34
  • 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
  • Slide 35
  • 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
  • Slide 36
  • Event-Driven Programming (continued)
  • Slide 37
  • 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
  • Slide 38
  • 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
  • Slide 39
  • 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
  • Slide 40
  • Improving GUI Layout More complex applications require more versatile GUIs The Java AWT provides tools for controlling a GUIs 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
  • Slide 41
  • 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
  • Slide 42
  • The FlowLayout Class The FlowLayout class arranges components within a containers 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 containers fixed width Example: A FlowLayout object, right-aligned FlowLayout fR = new FlowLayout(FlowLayout.RIGHT);
  • Slide 43
  • 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 containers size and frame size The NORTH and SOUTH components stretch horizontally The EAST and WEST components stretch vertically The CENTER component stretches both ways
  • Slide 44
  • The BorderLayout Class (continued)
  • Slide 45
  • 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
  • Slide 46
  • The BorderLayout Class (continued)
  • Slide 47
  • 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
  • Slide 48
  • Flowcharts for New Features of MusicWorldApp10.java
  • Slide 49
  • 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
  • Slide 50
  • 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
  • Slide 51
  • 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
  • Slide 52
  • 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
  • Slide 53
  • 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