42
GuiComp-1 For IST410 Students only GUI Component Library

GUI Component Library

  • Upload
    radha

  • View
    45

  • Download
    0

Embed Size (px)

DESCRIPTION

GUI Component Library. Objectives. Buttons CheckBox RadioButton List Text fields Menu and Menu Components Dialogs and File Dialogs. Swing Components. Swing defines a number of UI components These components can be used to capture data or issue commands - PowerPoint PPT Presentation

Citation preview

Page 1: GUI Component Library

GuiComp-1For IST410 Students only

GUI Component Library

Page 2: GUI Component Library

GuiComp-2For IST410 Students only

Objectives

Buttons CheckBox RadioButton List Text fields Menu and Menu Components Dialogs and File Dialogs

Page 3: GUI Component Library

GuiComp-3For IST410 Students only

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

Page 4: GUI Component Library

GuiComp-4For IST410 Students only

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

Page 5: GUI Component Library

GuiComp-5For IST410 Students only

Swing components and AWT

Swing components are generally thought of as JComponents.

AWT components are non-J componentsComponent Type Swing class AWT classButtons JButton ButtonCheck Box JCheckBox CheckBoxCheck box group JRadioButton CheckboxGroupFixed List JList ListMenu bar JMenuBar MenuBarMenu item JMenu MenuDialog JOptionPane

JDialogDialog

File dialog JFileChooser FileDialog

Page 6: GUI Component Library

GuiComp-6For IST410 Students only

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

Page 7: GUI Component Library

GuiComp-7For IST410 Students only

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 eventsprivate JButton btn;private ImageIcon im = new ImageIcon("banana.gif");private String lbl = "Banana”; btn = new JButton(lbl, im); btn.addActionListener(this);btn.setActionCommand(”banana");

The command string banana can then be used to find the event source

Page 8: GUI Component Library

GuiComp-8For IST410 Students only

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

Page 9: GUI Component Library

GuiComp-9For IST410 Students only

Instantiating Check Boxes

JCheckBox one, two; // declare two checkboxes .....

one = new JCheckBox("One",false); //not selected to start withone.addItemListener(this); // register listenercp.add(one,BorderLayout.NORTH); // add to the containertwo = 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

Page 10: GUI Component Library

GuiComp-10For IST410 Students only

ItemEvent with a Check Box

public void itemStateChanged(ItemEvent e) {JCheckBox s = (JCheckBox) e.getSource();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); else

jl.setIcon(bullet); }

} }

getSource returns the component that triggered the event; getText returns the label of the checkbox; SELECTED constant allows us to verify whether the checkbox is selected or not

Complete code in CheckBoxTest.java

Page 11: GUI Component Library

GuiComp-11For IST410 Students only

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

Page 12: GUI Component Library

GuiComp-12For IST410 Students only

Using Radio Buttons

Instantiate a button groupButtonGroup cbg = new ButtonGroup();

Instantiate radio buttons JRadioButton one = new JRadioButton("One",true);JRadioButton two = new JRadioButton(”Two",false);

Add buttons to the button groupcbg.add(one);cbg.add(two);

Register appropriate listeners with each Radio Buttonone.addItemListener(this);

Write event handers

Page 13: GUI Component Library

GuiComp-13For IST410 Students only

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{ jl.setIcon(canta); jl.setText("Button two clicked"); }

} }

Events originate from two different buttons;label icon is changedas a response. Full code inRadioButtonTest.java

Page 14: GUI Component Library

GuiComp-14For IST410 Students only

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

Lists

Page 15: GUI Component Library

GuiComp-15For IST410 Students only

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);

Selecting from a JList

Page 16: GUI Component Library

GuiComp-16For IST410 Students only

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

JList Event Handler

Page 17: GUI Component Library

GuiComp-17For IST410 Students only

public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { JList lst = (JList)e.getSource();

int firstIndex = lst.getSelectedIndex(); if (lst.isSelectionEmpty()) jl.setText("No list selection"); else jl.setText(items[firstIndex]+" selected");

}}

JList Event Handler

We delay responding to an event until the selection value has completed changing

Selected item is used to display a message using the JLabel. Complete example is in ListTest.java

Page 18: GUI Component Library

GuiComp-18For IST410 Students only

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

Text Field

Page 19: GUI Component Library

GuiComp-19For IST410 Students only

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 fieldtf.setText(“New text”);

Getting the text from a text fieldString 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

Instantiating a Text Field

Page 20: GUI Component Library

GuiComp-20For IST410 Students only

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

Page 21: GUI Component Library

GuiComp-21For IST410 Students only

JMenuBar

JMenuBar is the top level horizontal object in a menu system

Creating a menu bar objectJMenuBar 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

Page 22: GUI Component Library

GuiComp-22For IST410 Students only

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 barmb.add(mFile); //mb is the menu bar

A menu can be added to another menumFile.add(option);

A JSeparator object can be used create a horizontal separator among menus

Page 23: GUI Component Library

GuiComp-23For IST410 Students only

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

Page 24: GUI Component Library

GuiComp-24For IST410 Students only

Menu System Example: BasicMenu.java

JMenubar

JMenu

JMenuItem

Page 25: GUI Component Library

GuiComp-25For IST410 Students only

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(); }

Page 26: GUI Component Library

GuiComp-26For IST410 Students only

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);

Page 27: GUI Component Library

GuiComp-27For IST410 Students only

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);

Page 28: GUI Component Library

GuiComp-28For IST410 Students only

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"); }}

Page 29: GUI Component Library

GuiComp-29For IST410 Students only

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

Page 30: GUI Component Library

GuiComp-30For IST410 Students only

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

Page 31: GUI Component Library

GuiComp-31For IST410 Students only

Dialog: Example

import java.awt.*;import java.awt.event.*;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(); }}

MyDialog.java -called fromDialogFrame.java

Page 32: GUI Component Library

GuiComp-32For IST410 Students only

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);

Page 33: GUI Component Library

GuiComp-33For IST410 Students only

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

Page 34: GUI Component Library

GuiComp-34For IST410 Students only

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

Page 35: GUI Component Library

GuiComp-35For IST410 Students only

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

Page 36: GUI Component Library

GuiComp-36For IST410 Students only

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

Page 37: GUI Component Library

GuiComp-37For IST410 Students only

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);

Page 38: GUI Component Library

GuiComp-38For IST410 Students only

Dialog and FileChooser example

dlg = new JButton("Dialog"); //DialogFrame.javadlg.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);

Page 39: GUI Component Library

GuiComp-39For IST410 Students only

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());

Page 40: GUI Component Library

GuiComp-40For IST410 Students only

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); } }}

Page 41: GUI Component Library

GuiComp-41For IST410 Students only

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

Application 1

When button is pressed numbers in text fields are added and displayed in the last

text field

+

Action Button

Text Field

Page 42: GUI Component Library

GuiComp-42For IST410 Students only

Exercise

Application 2: Shows a list of gif files, when clicked the picture is displayed

List

Display area