Title: Basic Graphical User Interface Components
1Basic Graphical User Interface Components
- GUI components are visual objects that users
interact with using a mouse or keyboard - Java provides a standard set of platform
independent GUI components - Platform independent GUI programs make Java cool
2Basic Graphical User Interface Components
- C GUI programs are not easily moved from one
platform to another - How do we port a Window MFC based program to
Unix? - How do we port a Unix Motif based program to
Windows? - Javas GUI component classes are defined in
package javax.swing
3Basic Graphical User Interface Components
- All Java GUI objects inherit from class Component
- Key subclasses of Component include
- JButton a GUI push button
- JLabel a static text field
- JList a GUI list box
- JChoice a popup menu of choices
- JCheckbox a check box control
- JTextComponent the superclass of JTextField, a
single line text control, and JTextArea, a
multi-line text control
4Basic Graphical User Interface Components
- Component is an abstract base class that defines
many of the basic behaviors required of GUI
components such as paint or setSize
5class Container
- Another key class in java.awt is class Container
(which inherits from Component) - Container is the base class for GUI objects that
can contain and manage the layout of child GUI
objects - Class Applet is an indirect subclass of Container
6- Subclasses of Container include
- Panel the superclass of Applet
- Window the superclass of Dialog and Frame
- ScrollPane A container that provides scroll
bars - Container is an abstract base class
- defines behaviors required to manage collections
of children, such as add and remove
7Frames
import java.awt. class FrameTest extends Frame
public static void main(String args)
FrameTest ft new FrameTest()
ft.setSize(100,100) ft.setVisible(true)
- Frame is a subclass of Window
- Also see JFrame
- This sample code pops up an empty window
- You cant even kill it!
- (You havent told it how to handle a
window-closing event. More on that soon!)
8Frames
- setSize(x,y) gives the screen size of the window
- setVisible(boolean) makes a Component visible
9Labels
- Labels are read only text generally used to
display some caption or message in a GUI display - Create a Label by supplying a String to the Label
constructor - Can also specify the alignment of text within a
Label
Label ourlabel new Label("This is a Label")
10Labels
- getText and setText methods used to examine or
change the contents of a Label - Use the add method to add a Component to a
Container
ourlabel.setText(This is ourlabel.)
11Example
- ltcontainergt.add(ltlabelgt) // general form
- import java.awt.
- class FrameTestL extends Frame
- public static void main(String args)
- FrameTestL ft new FrameTestL()
- ft.setSize(100,100)
- Label ourlabel new Label(This is a
label.) - ft.add(ourlabel)
- ft.setVisible(true)
-
-
12Push Buttons
- A Button is a GUI object that a user clicks on to
trigger an action - Theyre created very similarly to Labels
- Heres FrameTest with a button instead of the
label
13Example
- import java.awt.
- class FrameTest extends Frame
- public static void main(String args)
- FrameTest ft new FrameTest()
- ft.setSize(100,100)
- Button ourbutton new Button(This is a
Button.) - ft.add(ourbutton)
- ft.setVisible(true)
-
-
14Push Button Code
- Try the code
- It doesnt do anything!
- When a Button is clicked, it generates an event
- But right now, no one is listening!
15Event-Driven Programming
- Theory Time
- GUI-driven programs use an Event-Driven execution
model - the system responds interactively to user input
- otherwise, little or nothing happens
- the Windows OS is an event-driven GUI application
16Event Driven.
- Events are discrete user actions
- mouse clicked
- key typed on keyboard
- focus gained (mouse cursor over window)
17Java Event Delegation
- Java uses events to handle user interaction
- Frame/Window/Applet passes event to a component
- The component notifies its registered Listeners
for that kind of event, using callback functions
18Java Event Delegation
- The listener(s) then process the event
- Events and Event Listeners are (surprise!) Java
objects - defined in package java.awt.event
- Referred to as Delegation because handling of
events is delegated to the listeners
19Events
- Event encapsulates information about an action
- Most have special methods that allow you to
obtain information about the event that was
generated - For instance, all awt events inherit method
getSource() from class Event - getSource() returns a reference to the object
that generated the event
20Events
- Example ActionEvent
- for high-level events, like GUI button presses
- Example MouseEvent
- for low-level events, like mouse motion and
clicks - getX()
- getY()
- getClickCount()
21Event Listeners
- An event listener object in Java is a object that
listens for specific types of events - Event listeners in Java typically implement a
particular Listener interface - A listener interface typically requires
implementation of one or more event handler
methods
22Event Listeners
- Event handler methods are known as callbacks
- listeners register callbacks with component
- Typically, this is done with some sort of
addXXXListener method of the component - when the event occurs, listeners are called
back with the event - It is these event handler methods that get
invoked when events occur in a GUI program - Example ActionListener (part of java.awt.event)
interface ActionListener extends EventListener
ActionPerformed (ActionEvent e)
23Back to Buttons
- When a Button is clicked, it generates an
ActionEvent object - The Button will pass the ActionEvent object along
to any listeners that have indicated to the
Button that they are interested in being notified
when the Button is clicked
24Back to Buttons
- Since Buttons generate ActionEvents, an
ActionListener object can be used to handle
Button click events - The ActionListener interface requires users to
implement only one method actionPerformed
25Example
- import java.awt.event.
- public class MyClickHandler implements
ActionListener - public void actionPerformed(ActionEvent e)
- System.out.println("You hit the button!")
-
-
26Listener Registration
- When we want to be notified of events that occur
in our GUI objects, we must register
appropriate listeners with those objects - For Button, ActionListeners register interest
with addActionListener - In this following example, each time the button
is clicked, the event is passed to MyClickHandler
27Example
- import java.awt.
- class ClickTest extends Frame
- public static void main(String args)
- // create our frame
- ClickTest ct new ClickTest()
- ct.setSize(100, 100)
- // create and add a new button
- Button b new Button("My Button")
- ct.add(b)
- // tell b to notify our listener of events
- b.addActionListener(new MyClickHandler())
- // show the frame
- ct.setVisible(true)
-
28Listener Registration
- A listener can handle events from one or many GUI
components - A GUI component can have 0, 1, or many listeners
for each event
29Window Management
- Now, lets add the ability to exit
- Clicking the X in the window title bar does not
close the window - It generates a window closing event
- All events need to be handled
- Need to register a WindowListener to be called
back when a WindowEvent of closing occurs
30Window Management
- Need to implement the WindowListener interface
- But WindowListener has so many functions!
- windowClosing, windowDeactivated,
windowDeiconified... - Whats a lazy graduate student to do?
31Listener Adapters
- Adapters are a shortcut for implementing Listener
interfaces - They implement all methods in the Interface with
a no-op - Then you can extend the Adapter and override the
functions you want - Could just implement the interface, write the
desired methods, and fill the others in with
32WindowListener
- We want to handle the closing event (when the X
is pushed) - Now we have two ways to write the code
- implement the entire WindowListener interface
- extend WindowAdapter and override the
windowClosing method
33Example
- public class WindowCloser implements
WindowListener -
- public void windowActivated(WindowEvent e)
- public void windowClosed(WindowEvent e)
- public void windowDeactivated(WindowEvent e)
- public void windowDeiconified(WindowEvent e)
- public void windowIconified(WindowEvent e)
- public void windowOpened(WindowEvent e)
- public void windowClosing(WindowEvent e)
- System.err.println("Closing!")
- System.exit(0)
-
-
- or
- public class WindowCloser extends WindowAdapter
- // other WindowListener methods set to
- public void windowClosing(WindowEvent e)
- System.err.println("Closing!")
- System.exit(0)
34Text Fields
- A TextField object represents a single line text
entry box - TextField extends TextComponent which is also the
base class for TextArea - TextFields generate ActionEvents when a user
presses the Enter key while typing within the
field
35Choice Buttons
Choice colors new Choice() Colors.add("red") C
olors.add("orange") Colors.add("yellow") Colors.
add("green") Colors.add("blue")
- Add strings to the end of a Choice object using
the add method - Retrieve items from a Choice object with the
getItem method
String item item colors.getItem(3) System.out.
println(item) //"green"
36Choice Buttons
- How to determine which item is selected in a
Choice object - The getSelectedIndex method returns the integer
index of the currently selected item in the
Choice object - The getSelectedItem method returns the String
value of the currently selected item in a Choice
object
37Choice Buttons
- Other content control methods
- remove(String str) removes the first occurrence
of the specified String object from the Choice
list - insert(String str, int index) insert the given
String at the specified index
38Choice Buttons
- Detecting changes in Choice boxes
- Choice buttons generate an ItemEvent whenever a
user selects a new value within the Choice list - Choice buttons send these ItemEvents to any
registered ItemListeners - ItemListeners need only implement one method
import java.awt.event. public class
ColorHandler implements ItemListener public
void itemStateChanged(ItemEvent e)
System.out.println(e.paramString())
39Checkboxes and Radio buttons
- The Checkbox class represents both checkbox and
radio button GUI objects - These buttons are state buttons. They represent
either true/false or on/off type values - radio-buttons are modeled after old-style radio
tuning buttons, where pushing any button unpushes
the others
40Checkboxes and Radio buttons
- These buttons generate ItemEvent objects when
they are selected or deselected. These ItemEvents
are sent to any registered ItemListeners - Radio buttons are a special form of Checkbox.
Related radio buttons are grouped together within
a CheckboxGroup - Only one button within a CheckboxGroup can be
selected at any one time
41Checkboxes and Radio buttons
- Useful Checkbox methods
- boolean getState() returns true if the Checkbox
is selected or false if it is not - String getLabel() returns the label of the
Checkbox - An ItemListener can handle Checkbox-generated
ItemEvents - Within an ItemListener, we are given the
opportunity to examine the ItemEvent generated by
our Checkbox objects
42Example
- import java.awt.event.
- public class CheckboxHandler implements
ItemListener - public void itemStateChanged(ItemEvent e)
- Checkbox cb (Checkbox) e.getSource()
- System.out.println(cb.getLabel()
- " state changed")
-
-
43Checkboxes and Radio buttons
- The cast to Checkbox above is safe as long as we
only register this class of ItemListener with
Checkbox objects
44Checkbox Example
- Creation of Checkbox objects, and registration of
an ItemListener for each
Frame buttons new Frame() buttons.setSize(200,2
00) // layout arranges the components more
on // this in the next lecture buttons.setLayout(n
ew FlowLayout()) Label caption caption
new Label("Which systems do you
use") buttons.add(caption, -1) Checkbox dos
new Checkbox("DOS") buttons.add(dos,
-1) Checkbox win31 new Checkbox("Windows
3.1") buttons.add(win31, -1) Checkbox win95
new Checkbox("Windows 95") buttons.add(win95,
-1) CheckboxHandler ch new CheckboxHandler
() dos.addItemListener(ch) win31.addItemListener
(ch) win95.addItemListener(ch) buttons.setVisibl
e(true)
45Creating radio buttons
- To create a group of radio buttons
- First create a CheckboxGroup to which the radio
buttons will belong
46Creating radio buttons
- Create the radio buttons using the 3 argument
constructor of Checkbox - Arg 1 is the label
- Arg 2 is the CheckboxGroup object from step one
- Arg 3 is a boolean indicating whether the button
should be initially selected or not - Add the radio buttons into a GUI container object
47Creating radio buttons
- Useful methods of the CheckboxGroup class
- Checkbox getSelectedCheckbox() returns the
currently selected Checkbox object - void setSelectedCheckbox(Checkbox) sets the
currently selected Checkbox in this group
48Example
- Frame colors new Frame()
- colors.setSize(200,200)
- colors.setLayout(new FlowLayout())
- Label caption
- caption new Label("Select your favorite
color") - colors.add(caption, -1)
- CheckboxGroup cg new CheckboxGroup()
- colors.add(new Checkbox("red", cg, false), -1)
- colors.add(new Checkbox("orange", cg, false),
-1) - colors.add(new Checkbox("yellow", cg, false),
-1) - colors.add(new Checkbox("green", cg, false), -1)
- colors.add(new Checkbox("blue", cg, false), -1)
- colors.setVisible(true)
49Single Selection Lists
- By default, only one item in the list can be
selected at any one time. This is a single
selection list
50Single Selection Lists
- A List object generates both ItemEvent and
ActionEvent objects - ItemEvents are generated when a user single
clicks on a choice in the list - ActionEvents are generated when a user double
clicks on a choice in the list. Since a single
click precedes a double click, the ActionEvent is
always preceded by an ItemEvent
51Single Selection Lists
- Useful List class methods
- String getItem(int index) return the list item at
position index - int getItemCount() returns the number of items in
the List - String getItems() returns a String array
containing all the items in the List
52Single Selection Lists
- String getSelectedItem() returns the String
representing the selected item in the List - void select(int index) select the item at the
specified index - Many more, see documentation
53Multiple-Selection Lists
- A List object can allow more than one item to be
selected at a time - Use the two argument constructor of List
54Multiple-Selection Lists
- Useful methods for multiple selection lists
- boolean isMultipleMode() returns true if the list
is a multiple selection list - String getSelectedItems() returns an array
containing the selected items in the list - int getSelectedIndexes() returns an array of
ints representing the indexes of the selected
items