Download Graphical User Interface - Accelerated Introduction to Computer Science | CS 201 and more Study notes Computer Science in PDF only on Docsity!
Chapter 12
Graphical User Interfaces
Topics
- GUI Applications with JFrame
- GUI Components
- JLabel
- Event Handling
- Layout Managers
- GUI Components
- Text Fields
- Command Buttons, Radio Buttons, and Checkboxes
- Lists and Combo Boxes
- Adapter Classes
- Mouse Movements
Introduction
- GUIs enable the user to
- select the next function to be performed
- enter data
- set program preferences, such as colors or fonts.
- GUIs also make the program easier to use
- a GUI is a familiar interface to users.
- Users can learn quickly to operate your program, in many cases, without consulting documentation or requiring extensive training.
GUI
- Presents a pictorial interface to a program
- It gives a program a distinct look and feel
- GUIs are built from a widgets – Window gadgets which are window components - Is an object with which the user interacts via the mouse, keyboard, voice recognition, etc
- Components Examples:
- JLabel
- JTextField
- JButton
- JCheckList
- JComboBox,
- JList
The JFrame Class
- The JFrame class, in the javax.swing package, allows you to display a window.
- JFrame is a
- Component , a graphical object that can be displayed
- Container , a component that holds other objects
- Window , a basic window
- Frame , a framed window
JFrame
- Is a window with a title bar and a border
- By default the window is hidden
- We specify action when the window is closed setDefaultCloseOperation - DISPOSE_ON_CLOSE - DO_NOTHING_ON_CLOSE - HIDE_ON_CLOSE - EXIT_ON_CLOSE
JFrame
- Window that knows how to resize itself
- Moves around on the screen when dragged
- Can minimize, maximize
Content Pane
JFrame Constructors
JFrame( String titleBarText ) constructs a JFrame object, initially invisible, with titleBarText displayed in the window's title bar
JFrame( ) constructs a JFrame object, initially invisible, with no text in the title bar
Constructor
GUI Components
- A component performs at least one of these functions: - displays information - collects data from the user - allows the user to initiate program functions
- The Java class library provides a number of component classes in the javax.swing package
AWT Versus Swing
- Java supports two implementations of GUI components: AWT (Abstract Window Toolkit) and swing.
- AWT components:
- the original implementation of Java components
- AWT hands off some of the display and behavior of the component to the native windowing system
- called heavyweight components
- Disadvantage:
- because of the inconsistencies in the look-and-feel of the various windowing systems, an application may behave slightly differently on one platform than on another.
AWT Versus Swing
- Swing Components
- second generation of GUI components
- developed entirely in Java to provide a consistent look and feel from platform to platform
- referred to as lightweight components
- Benefits:
- Applications run consistently across platforms, which makes maintenance easier.
- An application can take on the look-and-feel of the platform on which it is running, if desired.
Java Swing Components, part 1
Single-line text field for accepting passwords without displaying the characters typed.
Password field / JPasswordField
Multiple-line text field for data entry or display
Text area / JTextArea
A single-line text box for displaying information and accepting user input
Text field / JTextField
Displays an image or read-only text. Labels are often paired with text fields to identify the contents of the text field.
Label / JLabel
Component/ Purpose Java Class
Java Swing Components, part 2
Drop-down list of items that the user clicks to select one item
Drop-down List / JComboBox
List of items that the user clicks to select one or more items
List / JList
Toggle button that the user clicks to select 0, 1, or more options in a group.
Checkbox / JCheckBox
Toggle button that the user clicks to select one option in the group.
Radio Button / JRadioButton
Command button that the user clicks to signal that an operation should be performed
Button / JButton
Component/ Purpose Java Class
Useful JComponent Methods
setBackground( Color backColor ) sets the background color of the component to backColor.
void
setForeground( Color foreColor ) sets the foreground color of the component to foreColor.
void
setToolTipText( String toolTip ) sets the tool tip text to toolTip. When the mouse lingers over the component, the tool tip text will be displayed.
void
setVisible( boolean mode ) makes the component visible if mode is true ; hides the component if mode is false. The default is visible.
void
Return Method name and argument list value
More Useful JComponent Methods
setEnabled( boolean mode ) enables the component if mode is true , disables the component if mode is false. An enabled component can respond to user input.
void
setOpaque( boolean mode ) sets the component's background to opaque if mode is true ; sets the component's background to transparent if mode is false. If opaque, the component's background is filled with the component's background color; if transparent, the component's background is filled with the background color of the container on which it is placed. The default is transparent.
void
Return Method name and argument list value
Common Error
Trap
As for any object reference, you must instantiate a component before using it.
Forgetting to instantiate a component before adding it to the content pane will result in a NullPointerException at run time when the JVM attempts to display the component.
Common Error
Trap
Be sure to place the call to the setVisible method as the last statement in the constructor.
If you add components to the window after calling setVisible , those components will not be displayed until the window contents are refreshed, that is, not until the window is repainted.
Event Handling
- GUI programming uses an event-driven model of programming.
- The program responds to events caused by the user interacting with a GUI component. - For example, we might display some text fields, a few buttons, and a selectable list of items. Then our program will "sit back" and wait for the user to do something. - When the user enters text into a text field, presses a button, or selects an item from the list, our program will respond, performing the function that the user has requested, then sit back again and wait for the user to do something else.
Handling Events
- When the user interacts with a GUI component, the component fires an event.
- To allow a user to interact with our application through a GUI component, we need to perform the following functions: 1. write an event handler class (called a listener ) 2. instantiate an object of that listener 3. register the listener on one or more components
- An application can instantiate more than one event handler.
Listener Interfaces
- A typical event handler class implements a listener interface.
- The listener interfaces, which inherit from the EventListener interface, are supplied in the java.awt.event or javax.swing.event package.
- A listener interface specifies one or more abstract methods that an event handler class needs to override.
- The listener methods receive as a parameter an event object, which represents the event that was fired.
Event Objects
- Event classes are subclasses of the EventObject class and are in the java.awt.event and javax.swing.event packages.
- From the EventObject class, event classes inherit the getSource method.
- With simple if .. else if statements, an event handler can identify which of its registered components fired the event.
Object
Return value getSource( ) returns the object reference of the component that fired the event
Method name and argument list
Events and Listeners
Selecting a ItemEvent^ ItemListener checkbox
JCheckBox
Selecting a ItemEvent ItemListener radio button
JRadioButton
Pressing the ActionEvent ActionListener button
JButton
Pressing ActionEvent ActionListener Enter
JTextArea
Pressing ActionEvent ActionListener Enter
JTextField
Listener Interface to Implement
JComponent User ActivityEvent Object
Event Handler Pattern
- Event handler as a private inner class. private class EventHandlerName implements ListenerName { // implement the listener interface methods // to process the events }
- A private inner class is defined within the public class and has access to all the members of the public class.
- When an event is fired on a registered component, the appropriate listener methods executes automatically.
Text Fields
- We will write a GUI program that simulates a login. We will use these components: - JTextField (a single line of text) for the User ID - JPasswordField (a single line of text that echoes a special character for each character typed by the used) for the password - JTextArea (multiple lines of text) to display a legal warning to potential hackers
JTextField and JPasswordField
Constructors
JPasswordField JPasswordField( int numberColumns ) constructs an empty password field with the specified number of columns
JTextField( int numberColumns ) constructs an empty text field with the specified number of columns
JTextField( String text ) creates a text field initially filled with text
JTextField
JTextArea Constructors
JTextArea( String text, int numRows, int numColumns ) constructs a text area initially filled with text , and with the number of rows and columns specified by numRows and numColumns
JTextArea( int numRows, int numColumns ) constructs an empty text area with the number of rows and columns specified by numRows and numColumns
JTextArea( String text ) constructs a text area initially filled with text
Methods Common to JTextField ,
JTextArea , & JPasswordField
getText( ) returns the text contained in the text component
String
setText( String newText ) sets the text of the text component to newText
void
setEditable( boolean mode ) sets the properties of the text component as editable or noneditable, depending on whether mode is true or false. The default is editable.
void
Return Method name and argument list value
Additional Methods of the
JPasswordField Class
getPassword( ) returns the text entered in this password field as an array of chars. Note: this method is preferred over the getText method for retrieving the password typed by the user.
char []
setEchoChar( char c ) sets the echo character of the password field to c
void
Return Method name and argument list value
The ActionListener Interface
- An event handler that implements the ActionListener interface provides code in this method to respond to the ActionEvent fired by any registered components.
public void actionPerformed( ActionEvent event )
- See Example 12.3 Login.java
Common Error
Trap
Be sure that the header of the listener method you override is coded correctly. Otherwise, your method will not override the abstract method, as required by the interface. For example, misspelling the actionPerformed method name as in this header: public void actionperformed( ActionEvent a ) will generate a compiler error: Login.TextFieldHandler is not abstract and does not override abstract method actionPerformed(java.awt.event.ActionEvent) in java.awt.event.ActionListener
The ButtonGroup Class
- Then we instantiate a ButtonGroup and add the buttons to the group.
- A ButtonGroup object is used to define a mutually exclusive group of buttons.
ButtonGroup( ) constructs a button group
Constructor
void
Return value add( AbstractButton button ) adds button to the button group. JRadioButton inherits from AbstractButton.
Method name and argument list
The ItemListener Interface
- Clicking on a registered JRadioButton or a JCheckBox generates an ItemEvent , which is handled by an ItemListener.
- An event handler that implements the ItemListener interface provides code in this method to respond to the ItemEvent fired by any registered components.
public void itemStateChanged( ItemEvent event )
- See Example 12.5 ChangingColors.java
A Useful ItemEvent Method
- Each click on a registered JCheckBox generates an ItemEvent. Thus, an event is generated when the JCheckBox is selected and also when the JCheckBox is deselected.
- To distinguish between these states, we call the getStateChange method of the ItemEvent class.
int
Return value getStateChange( ) If the checkbox is selected, the value SELECTED is returned; if the checkbox is deselected, the value DESELECTED is returned, where SELECTED and DESELECTED are static int constants of the ItemEvent class.
Method name and argument list
JCheckBox Constructors
- Because JCheckBoxes are designed to allow selection of multiple check boxes simultaneously, we do not use a button group.
- See Example 12.6 MixingColors.java
JCheckBox( String checkBoxLabel, boolean selected ) constructs a checkbox labeled checkBoxLabel. If selected is true , the checkbox is initially selected; if selected is false , the checkbox is initially deselected.
JCheckBox( String checkBoxLabel ) constructs a check box labeled checkBoxLabel. By default, the check box is initially deselected.
JCheckBox Constructors
The JList Component
- The JList component displays a list of items.
- The user can select one or more items from the list, depending on the selection mode.
- When an item is selected on a registered list, a ListSelectionEvent is generated.
- The listener for this event implements the ListSelectionListener interface, which has one method:
public void valueChanged( ListSelectionEvent e )
JList Constructor and Methods
JList( Object [] arrayName ) constructs a JList initially filled with the objects in arrayName. Often, the objects are Strings.
Constructor
setSelectedIndex( int index ) selects the item at index. The index of the first item in the list is 0.
void
int
Return value getSelectedIndex( ) returns the index of the selected item. The index of the first item in the list is 0.
Method name and argument list
Another JList Method
- See Example 12.8 FoodSamplings.java
void
Return value setSelectionMode( int selectionMode ) sets the number of selections that can be made at one time. The following static int constants of the ListSelectionModel interface can be used to set the selection mode: SINGLE_SELECTION – one item can be selected SINGLE_INTERVAL_SELECTION – multiple contiguous items can be selected MULTIPLE_INTERVAL_SELECTION – multiple intervals of contiguous items can be selected (This is the default.)
Method name and argument list
Software Engineering
Tip
Arrange items in lists in a logical order so that the user can find the desired item quickly.
For example, list items alphabetically or in numeric order.
Also consider placing the most commonly chosen items at the top of the list.
Adapter Classes
- For convenience, Java provides adapter classes , each of which implements an interface and provides an empty body for each of the interface's methods.
- For mouse events, the adapter classes are
- MouseAdapter, which implements the MouseListener interface
- MouseMotionAdapter, which implements the MouseMotionListener interface
- Thus, instead of implementing an interface, we can extend the appropriate adapter class and override only the method or methods we need.
MouseEvents
- Any mouse activity (clicking, moving, or dragging) by the user generates a MouseEvent.
- To determine the (x, y) coordinate of the mouse event, we can call these methods of the MouseEvent class:
getY( ) returns the y value of the (x, y) coordinate of the mouse activity
int
int
Return value getX( ) returns the x value of the (x, y) coordinate of the mouse activity
Method name and argument list
MouseListener Interface Methods
public void mouseExited( MouseEvent e ) called when the mouse exits the registered component
public void mouseEntered( MouseEvent e ) called when the mouse enters the registered component
public void mouseClicked( MouseEvent e ) called when the mouse button is pressed and released
public void mouseReleased( MouseEvent e ) called when the mouse is released after being pressed
public void mousePressed( MouseEvent e ) called when the mouse button is pressed
Using the MouseAdapter Class
- We implement a Submarine Hunt game.
- A submarine is hidden somewhere in the window, and the user will try to sink the submarine by clicking the mouse at various locations in the window, simulating the dropping of a depth charge.
- The only mouse action we care about is a click; therefore, we are interested in overriding only one method of the MouseListener interface: mouseClicked. To simplify our code, we extend the MouseAdapter class.
- The listener should handle mouse clicks anywhere in the window, so we register the mouseListener mh on the window ( JFrame ) component: this.addMouseListener( mh );
Removing a Listener
- In the mouse handler, if the mouse click has hit the submarine, we "unregister" the mouse listener using the following method inherited from the C omponent class. After doing so, further mouse clicks will no longer cause the handler to be called.
void
Return value
removeMouseListener( MouseListener mh ) removes the mouse listener mh so that it is no longer registered on this component.
Method name and argument list
Updating the Window
- Two cases require us to update the window:
- When the submarine has been hit, we want to draw the "sunken" submarine
- If the mouse click is more than two lengths from the center of the submarine, we want to draw a blue circle
- However, we cannot call the paint method explicitly. Instead, we call the repaint method (inherited from the Component class):
- See Example 12.12 SubHunt.java
void
Return value repaint( ) automatically forces a call to the paint method
Method name and argument list
A Treasure Hunt Game
- We implement a treasure hunt game:
- we hide a treasure in the window.
- the user attempts to find the treasure by moving the mouse around the window.
- we indicate how close the mouse is to the treasure by printing a message at the mouse location.
- when the user moves the mouse over the treasure, we draw the treasure and remove the listener to end the game.
We Use the MouseMotionListener
Interface
- Instead of coding the event handler as a private inner class, we define our application class as implementing the MouseMotionListener interface. As a result, our application is a listener, and we register the listener on itself: this.addMouseMotionListener( this );
- See Example 12.13 TreasureHunt.java
public void mouseDragged( MouseEvent e ) called when the mouse is pressed on a registered component and the mouse is dragged
public void mouseMoved( MouseEvent e ) called when the mouse is moved onto a registered component
BorderLayout
- A BorderLayout organizes a container into five areas:
- Each area can hold at most one component.
- The size of each area expands or contracts depending on: - the size of the component in that area - the sizes of the components in the other areas - whether the other areas contain a component.
SOUTH
WEST CENTER EAST
NORTH
Using a BorderLayout
- BorderLayout is the default layout manager for a JFrame object. - so if we want to use a border layout for our GUI applications, we do not need to instantiate a new layout manager.
BorderLayout( int hGap, int vGap ) creates a border layout with a horizontal gap of hGap pixels between components and a vertical gap of vGap pixels between components.
BorderLayout( ) creates a border layout with no gaps between components
BorderLayout Constructors
Adding Components to a
BorderLayout
- To add components to a container with a BorderLayout layout manager, we use this method inherited from the Container class.
- See Example 12.16 BridgeBidding.java
void
Return value add( Component c, Object borderlayoutArea ) adds the component c to the container. The area defined by borderlayoutArea can be specified using any of the following static String constants from the BorderLayout class: NORTH, SOUTH, EAST, WEST, CENTER
Method name and argument list
Nesting Components
- Components can be nested.
- Because the JComponent class is a subclass of the Container class, a JComponent object is a Container object as well. As such, it can contain other components.
- We can use this feature to nest components to achieve more precise layouts.
Using JPanels to Nest Components
- The JPanel class is a general-purpose container, or a panel , and is typically used to hold other components.
- We usually place several components into a JPanel , then add the JPanel to the container as a single component.
- Each JPanel has its own layout manager, and the content pane for the JFrame application has its own layout manager.
- We can even have multiple levels of nesting.
Example 12.17 BridgeRules.java
- The content pane has a GridLayout layout (1 row, 2 columns)
- We define a JPanel managed by a GridLayout (5 rows, 1 column). We added five buttons to the JPanel and add the JPanel to column 1 of the content pane.
- We define a second JPanel managed by a BorderLayout. We put a component into each of the five BorderLayout areas and add the JPanel to column 2 of the content pane.
BackUp
Import Classes & Declare Fields
- Import package containing the JFrame class
import javax.swing.*;
- Declare a variable of class JFrame JFrame outFrame;
- Declare a variable of the class Container Container outPane;