GUI Components

Download Report

Transcript GUI Components

GUI Component Library
For IST410 Students only
GuiComp-1
Objectives







Buttons
CheckBox
RadioButton
List
Text fields
Menu and Menu Components
Dialogs and File Dialogs
For IST410 Students only
GuiComp-2
Swing Components



Swing defines a number of UI components
These components can be used to capture data or issue
commands
Some of the more common components are








Buttons
Check Boxes - or toggles
Radio Buttons - same as check boxes, but are grouped together
Lists
Text fields
Menus and its subcomponents
Dialogs
File Dialog
For IST410 Students only
GuiComp-3
Swing Components





Most of the components discussed in this module are light
weight components
They need to be added on to a container such as a JFrame
or JPanel
We can use action events for many of them
Where appropriate, we refer to other type of event handlers
For each component type included in this module, we
show how a component is instantiated, how it is added to a
container and where appropriate, how an event handler is
registered for the component
For IST410 Students only
GuiComp-4
Swing components and AWT


Swing components are generally thought of as
JComponents.
AWT components are non-J components
Component Type
Buttons
Check Box
Check box group
Fixed List
Menu bar
Menu item
Dialog
File dialog
Swing class
JButton
JCheckBox
JRadioButton
JList
JMenuBar
JMenu
JOptionPane
JDialog
JFileChooser
AWT class
Button
CheckBox
CheckboxGroup
List
MenuBar
Menu
Dialog
FileDialog
For IST410 Students only
GuiComp-5
Inheritance hierarchy of UI Components




All JComponents included in this module are derived from
the javax.swing.JComponent class (hence the name
JComponents)
JComponent is itself a subclass of java.awt.Container
This hierarchy needs to be remembered while searching for
methods that apply to these components since the method
may be inherited
Non-J UI components derive from java.awt.Component.
Thus, most discussion in this module apply to
corresponding awt UI components
For IST410 Students only
GuiComp-6
JButtons


We have seen JButton Constructors in previous modules
and have used them in various example programs
We have also seen how we can register action listeners
with buttons as well as monitor for button events
private JButton btn;
private ImageIcon im = new ImageIcon("banana.gif");
private String lbl = "Banana”;
btn = new JButton(lbl, im);
The command string
banana can then be
btn.addActionListener(this);
used to find the event
source
btn.setActionCommand(”banana");
For IST410 Students only
GuiComp-7
Check Boxes





JCheckBox implements check boxes in Swing
Check boxes provide a toggle capability and can be used to
indicate yes/no type of data items
The state of selection can be monitored through
ItemListener interface.
There are 7 constructors in this class that gives the user an
option to instantiate check box objects with Text and Icon
labels. Initial state of the boxes can be set to selected or
not-selected through the constructor
CheckBoxes can be monitored using ItemListener and
ActionListener interfaces
For IST410 Students only
GuiComp-8
Instantiating Check Boxes
JCheckBox one, two;
// declare two checkboxes
.....
one = new JCheckBox("One",false); //not selected to start with
one.addItemListener(this);
// register listener
cp.add(one,BorderLayout.NORTH); // add to the container
two = new JCheckBox("two",true);
two.addItemListener(this);
cp.add(two,BorderLayout.SOUTH);


ItemEvent has exactly one method: itemStateChanged
Using ItemEvent, we can check for the selection state of a
check box; getText() method gives us the name of the
check box itself
For IST410 Students only
GuiComp-9
ItemEvent with a Check Box
public void itemStateChanged(ItemEvent e) {
Complete code in
JCheckBox s = (JCheckBox) e.getSource();
CheckBoxTest.java
String cblbl = s.getText();
if (cblbl.equals("one") && e.getStateChange() == ItemEvent.SELECTED) {
System.out.println("Checkbox "+cblbl+" selected");
}
else {
if (cblbl.equals("two")) {
if (e.getStateChange() == ItemEvent.SELECTED)
jl.setIcon(middle); getSource returns the component that
else
triggered the event; getText returns the
jl.setIcon(bullet);
label of the checkbox; SELECTED
}
constant allows us to verify whether the
}
checkbox is selected or not
}
For IST410 Students only
GuiComp-10
Radio Buttons







Radio Buttons are new in Swing; does not exits in AWT
Just like Check Boxes, Radio Buttons are toggles
Radio Buttons are employed in a group and only one
button from the group can be selected at any time
Groups of Radio Buttons are created using a container
object of type ButtonGroup
Radio Buttons can be monitored through more than one
listener including ItemListener and ActionListener
Radio Buttons can be instantiated with string , icon or
combination of string and icon labels
There are 7 different constructors
For IST410 Students only
GuiComp-11
Using Radio Buttons





Instantiate a button group
ButtonGroup cbg = new ButtonGroup();
Instantiate radio buttons
JRadioButton one = new JRadioButton("One",true);
JRadioButton two = new JRadioButton(”Two",false);
Add buttons to the button group
cbg.add(one);
cbg.add(two);
Register appropriate listeners with each Radio Button
one.addItemListener(this);
Write event handers
For IST410 Students only
GuiComp-12
Event Handling: Radio Buttons
public void itemStateChanged(ItemEvent e) {
JRadioButton s = (JRadioButton) e.getSource();
String st = s.getText();
if (e.getStateChange() == ItemEvent.SELECTED) {
if (st.equals("One")){
jl.setIcon(ban);
jl.setText("Button one clicked");
System.out.println("RadioButton "+st+" selected");
} else{
Events originate from
jl.setIcon(canta);
two different buttons;
jl.setText("Button two clicked");
label icon is changed
}
as a response. Full code in
}
RadioButtonTest.java
}
For IST410 Students only
GuiComp-13
Lists





Lists are components that allow the user to select one or
more items from a list
Lists are implemented using JList class in Swing
A JList is used as a data entry UI component where the
user can be presented with a predefined list of choices, the
user may choose one or many
The selectable items in a list are elements of an Object
array and remain displayed on the GUI interface
A List can be made scrollable by placing it inside a
JScrollPane or SrollPane
For IST410 Students only
GuiComp-14
Selecting from a JList



If the user is allowed to choose only one item, it is a case
of Single Selection Model; otherwise it is a multiple
selection model; multiple selection can be in a single
contiguous group or multiple groups
JList has 4 constructors
Instantiating a JList object
String [] items = {"Mercury","Venus","Earth","Mars",
"Jupiter","Saturn","Neptune" };
JList lst = new JList(items);

Since one or more items can be selected, we specify a
selection model. However, by default it is single selection
lst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
For IST410 Students only
GuiComp-15
JList Event Handler





A number of event handlers can be registered with a list.
We use the ListSelectionListener which is called every
time the value of selection changes
lst.addListSelectionListener(this);
We can use getSelectedIndex() method of the list object to
determine the selected item
ListSelection events are also fired when the selection is in
the process of changing
If we are interested in the changing process, we can use the
getValueIsAdjusting() method of the ListSelection event
For IST410 Students only
GuiComp-16
JList Event Handler
public void valueChanged(ListSelectionEvent e) {
We delay responding to an
if (!e.getValueIsAdjusting()) {
event until the selection
JList lst = (JList)e.getSource();
value has completed
int firstIndex = lst.getSelectedIndex(); changing
if (lst.isSelectionEmpty())
Selected item is used to
a message using the
jl.setText("No list selection"); display
JLabel. Complete example is
in ListTest.java
else
jl.setText(items[firstIndex]+" selected");
}
}
For IST410 Students only
GuiComp-17
Text Field






Text Fields are created with the JTextField class
JTextField is a light weight component that allows the
editing of a single line of text
We have already seen usage of text fields in previous
examples; here we look at the essential code required for
creating and using a text field object
There are 5 constructors of JTextField
These constructors can be used to instantiate a text field
object with an initial text and / or a column size
If the column size is used, think of the size as a display
window for the text, and not a limit to the number of text
characters that can be entered into a text field
For IST410 Students only
GuiComp-18
Instantiating a Text Field





Constructing text field object
JTextField tf = new JTextField(“Hello”);
JTextField tf = new JTextField(30);
JTextField tf = new JTextField(“Hello”,30);
Inserting a string in a text field
tf.setText(“New text”);
Getting the text from a text field
String s = tf.getText();
Action events can be monitored from a text field and
setActionCommand can be used to set a command string
TextListener can be used to monitor changes in the text
field
For IST410 Students only
GuiComp-19
Menu





Menu systems are special in Java; they get added to the
frame itself
The JMenuBar defines the highest level component in a
menu system and provides a container for menus in the
menu system
JMenus are the basic selectable menus that can be added to
the menu bar, or other JMenu
Selection of a JMenu results in a drop-down list that can
contain JMenu or JMenuItem objects
ActionEvent listener can be registered with menu items
For IST410 Students only
GuiComp-20
JMenuBar



JMenuBar is the top level horizontal object in a menu
system
Creating a menu bar object
JMenuBar mb = new JMenuBar();
The menu bar needs a special method to be declared as the
top level menu
jf.setJMenuBar(mb); //jf is a JFrame object
For IST410 Students only
GuiComp-21
JMenu






JMenu is added to a JMenuBar or another JMenu
JMenu is the anchor to a drop-down menu item list
Creating a menu
JMenu mFile = new JMenu("File");
JMenu option = new JMenu(”Option");
The menu can be added to a menu bar
mb.add(mFile);
//mb is the menu bar
A menu can be added to another menu
mFile.add(option);
A JSeparator object can be used create a horizontal
separator among menus
For IST410 Students only
GuiComp-22
JMenuItem







JMenuItem is added to a JMenu
A JMenuItem object can be created with a text label, an
icon label, or a combination of text and icon
Creating a menu item
JMenuItem miOpen = new JMenuItem("Open");
A menu item is added to a menu
mFile.add(miOpen); //mFile is a menu
Event handlers are registered with menu items
miOpen.addActionListener(handler);
Any number of menu items can be added to a menu
We look at an example next: BasicMenu.java
For IST410 Students only
GuiComp-23
Menu System Example: BasicMenu.java
JMenu
JMenuItem
JMenubar
For IST410 Students only
GuiComp-24
Example: BasicMenu.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BasicMenu extends JFrame implements ActionListener {
private Container cp;
private JMenuBar mb;
private JMenu mFile, mEdit, mHelp;
private JMenuItem miOpen, miDisplay, miQuit, miList;
private JMenuItem miHelp;
private JLabel lbl;
public static void main(String [] args) {
BasicMenu mm = new BasicMenu();
}
For IST410 Students only
GuiComp-25
Example: BasicMenu.java
public BasicMenu() {
// BasicMenu.java
setTitle("Mini Application Menu System");
cp = getContentPane();
setSize(500,400);
lbl = new JLabel("Welcome to Menu System example");
lbl.setHorizontalAlignment(SwingConstants.CENTER);
lbl.setForeground(Color.blue);
lbl.setFont(new Font("Helvetica",Font.BOLD,26));
cp.add(lbl, BorderLayout.CENTER);
mb = new JMenuBar();
//Menu bar
mFile = new JMenu("File"); // Menus
mEdit = new JMenu("Edit");
mHelp = new JMenu("Help");
mb.add(mFile);
mb.add(mEdit);
mb.add(mHelp);
For IST410 Students only
GuiComp-26
Example: BasicMenu.java
miOpen = new JMenuItem("Open");
// BasicMenu.java
miDisplay = new JMenuItem("Display");
miQuit = new JMenuItem("Quit");
miOpen.addActionListener(this);
miDisplay.addActionListener(this);
miQuit.addActionListener(this);
mFile.add(miOpen);
mFile.add(miDisplay);
mFile.add(miQuit);
miList = new JMenuItem("List");
miList.addActionListener(this);
mEdit.add(miList);
miHelp = new JMenuItem("Message");
miHelp.addActionListener(this);
mHelp.add(miHelp);
For IST410 Students only
GuiComp-27
Example: BasicMenu.java
setJMenuBar(mb);
addWindowListener(new MyWindowAdapter());
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String ac = e.getActionCommand();
System.out.println("Menu item "+ac+" chosen");
}
}
For IST410 Students only
GuiComp-28
Dialogs





Dialogs are frames that are often used as pop-up windows
Dialogs can display messages or take user’s input
They can be modal or non-modal. A user must close a
modal dialog before changing the focus to some other
component on the screen. Non-modal dialogs do not
impose such a restriction
Dialogs can be created with Dialog class in AWT, JDialog
and JOptionPane classes in Swing
Dialog and JDialog do not have any built-in controls;
JOptionPane offers a limited set of built-in controls
For IST410 Students only
GuiComp-29
Dialogs

An AWT style dialog is built by extending java.awt.Dialog
public class MyDialog extends Dialog implements ActionListener { ... }


A dialog object is created as a window within another
dialog or a frame. The choice of constructor determines
this.
To create a dialog within the frame of another application
public MyDialog(Frame f, String title, boolean modal) { .. }


We can add controls and event handlers to a dialog frame
as needed
setVisible(true) is used to display the dialog;
setVisible(false) hides the dialog without releasing it from
memory
For IST410 Students only
GuiComp-30
Dialog: Example
import java.awt.*;
MyDialog.java -called from
import java.awt.event.*;
DialogFrame.java
import javax.swing.*;
public class MyDialog extends Dialog implements ActionListener {
private Button bOK;
public MyDialog(Frame f, String title, boolean modal, String msg) {
super(f,title,modal);
setSize(150,200);
add(new Label(msg,Label.CENTER),BorderLayout.CENTER);
bOK = new Button("OK");
add(bOK,BorderLayout.SOUTH);
bOK.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
dispose();
}
}
For IST410 Students only
GuiComp-31
JOptionPane
This is a Swing class that can be used to display standard
dialog boxes that prompts the user for a value, or displays
some information
 The JOptionPane class has a large number of methods
through which dialogs of various types can be constructed
 For example, to show a message that informs the user of
something, we can use the showMessageDialog
JOptionPane.showMessageDialog(this,"Simple Dialog shown
in a modal frame", "Information",
JOptionPane.DEFAULT_OPTION);

For IST410 Students only
GuiComp-32
JOptionPane


Dialogs using option panes are all
modal, execution of the program stops
until the user closes the dialog frame
Parameters used in the
showMessageDialog

this - The supervisory frame; the
dialog is displayed in this frame

“Simple Dialog ...” - The message
to be displayed in the dialog box

“Information” - The title of the
dialog box

JOptionPane.DEFAULT_OPTION
- Default options available in the
JOptionPane class is chosen - Sets
up buttons and handlers
For IST410 Students only
GuiComp-33
JFileChooser


JFileChooser is a successor of FileDialog class
JFileChooser can be used to display a file dialog
MS Window 98
style file dialog:
result of
JFileChooser use
For IST410 Students only
GuiComp-34
JFileChooser
A file chooser object can be created through the
FileSystemView
JFileChooser fd =
new JFileChooser(FileSystemView.getFileSystemView());
 The file dialog box itself is shown by calling open dialog
int chrslt = fd.showOpenDialog(this);
 The return value from open dialog indicates whether user
selected a file (APPROVE_OPTION) or cancelled
(CANCEL_OPTION)
 Further file related activity can then be done using the file
chooser object

For IST410 Students only
GuiComp-35
Dialog and FileChooser example






We show an example of creating 3 types of dialogs in
DialogFrame.java
This program creates a frame and instantiates 4 buttons.
Buttons are appropriately labeled
When clicked, these buttons respond by displaying an
AWT style dialog, a Swing style dialog (JOptionPane) and
a file dialog (JFileChooser)
A quit button is used to exit from the demo program
MyDialog.java is used to construct the AWT style dialog
For IST410 Students only
GuiComp-36
Dialog and FileChooser example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.*;
public class DialogFrame extends JFrame implements ActionListener{
private Container cp;
private JButton dlg, dopt, dflc;
private JButton quit;
public static void main(String [] args) {
DialogFrame mm = new DialogFrame();
}
public DialogFrame() {
setTitle("Dialog chooser");
cp = getContentPane();
setSize(500,400);
For IST410 Students only
GuiComp-37
Dialog and FileChooser example
dlg = new JButton("Dialog");
//DialogFrame.java
dlg.setActionCommand("DLG");
dlg.addActionListener(this);
dopt = new JButton("Option Pane");
dopt.setActionCommand("OPT");
dopt.addActionListener(this);
dflc = new JButton("File Chooser");
dflc.setActionCommand("FLD");
dflc.addActionListener(this);
quit = new JButton("Quit");
quit.addActionListener(this);
cp.setLayout(new FlowLayout());
cp.add(dlg);
cp.add(dopt);
cp.add(dflc);
cp.add(quit);
For IST410 Students only
GuiComp-38
Dialog and FileChooser example
addWindowListener(new MyWindowAdapter()); //DialogFrame.java
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String ac = e.getActionCommand();
if ("DLG".equals(ac)) {
MyDialog d = new MyDialog(this, "Dialog", true, "This is a Dialog");
d.setVisible(true);
} else if ("OPT".equals(ac)) {
JOptionPane.showMessageDialog(this,"Simple Dialog shown in a
modal frame","Information", JOptionPane.DEFAULT_OPTION);
} else if ("FLD".equals(ac)) {
JFileChooser fd = new JFileChooser(
FileSystemView.getFileSystemView());
For IST410 Students only
GuiComp-39
Dialog and FileChooser example
int chrslt = fd.showOpenDialog(this);
//DialogFrame.java
if (chrslt == JFileChooser.APPROVE_OPTION){
File f = fd.getSelectedFile();
System.out.println("File selected is "+f.getName());
}
} else if ("Quit".equals(ac)) {
System.exit(0);
}
}
}
For IST410 Students only
GuiComp-40
Exercise



For this exercise, create an application that has a main
menu bar with one menu. This menu has two menu items.
When clicked, each menu item brings up a simple
application as shown here
Text
Field
Application 1
+
When button is pressed
Action Button
numbers in text fields are added and displayed in the last
text field
For IST410 Students only
GuiComp-41
Exercise

Application 2: Shows a list of gif files, when clicked the
picture is displayed
Display
area
List
For IST410 Students only
GuiComp-42