pageumpeysak/classes/gui/lectures/cs338-l4… · page ‹#› cs 338: graphical user interfaces....

25
Page ‹#› 1 CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 4: Components CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 2 Widgets! Look at the most common GUI components see what they do see how they work High-level goal: Get prepared to build a real interface! CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 3 Swing components Component hierarchy Top-level Containers (frame, dialog, applet, …) Intermediate Containers (panel, scroll pane, …) Atomic Components (button, list, menu, …) javax.swing. JComponent java.awt. Window CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 4 Buttons Something that invokes an action/command or changes system state “OK” / “Cancel” “New Folder” File type: “Word 98” Visual design based on real-world buttons physical mouse click also resembles button push! (the power of metaphors…)

Upload: others

Post on 21-Sep-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

1CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University.

Lecture 4:Components

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 2

Widgets!

• Look at the most common GUI components– see what they do– see how they work

• High-level goal:Get prepared to build a real interface!

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 3

Swing components

• Component hierarchy

Top-level Containers(frame, dialog, applet, …)

Intermediate Containers(panel, scroll pane, …)

Atomic Components(button, list, menu, …)

javax.swing.JComponent

java.awt.Window

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 4

Buttons

• Something that invokes an action/commandor changes system state– “OK” / “Cancel”– “New Folder”– File type: “Word 98”

• Visual design based on real-world buttons– physical mouse click also resembles button push!

(the power of metaphors…)

Page 2: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5

Buttons

• AbstractButton = abstract parent class– JButton– JCheckBox– JRadioButton– JMenuItem– and more…

• Side note: AbstractButton is anabstract class, not an interface

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 6

All Buttons

• Can contain both text and icon

• What’s an icon?

ImageIcon leftButtonIcon = new ImageIcon ("images/right.gif");

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 7

All Buttons

• Placing text in the buttons

• Enabling / disabling buttons (important!!)b.setEnabled (true);

(false);

b.setHorizontalTextPosition (AbstractButton.CENTER);(AbstractButton.LEFT);(AbstractButton.RIGHT);

b.setVerticalTextPosition (AbstractButton.CENTER);(AbstractButton.TOP);(AbstractButton.BOTTOM);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 8

All Buttons

• Noting the “Action Command”– string that denotes what the button does

– can be used in handling events

b3.setActionCommand (“disable”);

public void actionPerformed(java.awt.event.ActionEvent e) { if (e.getActionCommand().equals("disable")) { b2.setEnabled(false); b1.setEnabled(false); b3.setEnabled(true); } else { b2.setEnabled(true); b1.setEnabled(true); b3.setEnabled(false); } }

Page 3: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 9

All Buttons

• Associating keys

• Attaching “tool tips”

b1.setMnemonic (KeyEvent.VK_D);b2.setMnemonic (KeyEvent.VK_M);b3.setMnemonic (KeyEvent.VK_E);

b1.setToolTipText ("Click this button to disable the middle button.");b2.setToolTipText ("This middle button does nothing when you click it.");b3.setToolTipText ("Click this button to enable the middle button.");

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 10

JButton

• Our old friend...

• ConstructorsJButton () // Creates a plain button, no icon or textJButton (Icon icon) // Creates a button with an icon.JButton (String text) // Creates a button with text.JButton (String text, Icon icon) // Creates a button with initial text and an icon

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 11

JButton

• Setting the default button (for “Return” key)

getRootPane().setDefaultButton (setButton);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 12

JButton

• Using HTML in the button label(Only later versions! >= Swing 1.1.1B of JFC 1.1)

b1 = new JButton ("<html><font size=-1><b><u>D</u>isable</b>middle button</font>", leftButtonIcon);b2 = new JButton("<html><font size=-1>Middle button</font>", middleButtonIcon);b3 = new JButton("<html><font size=-1><b><u>E</u>nable</b>middle button</font>", rightButtonIcon);

Page 4: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 13

JButton

• Handling events…

button. addActionListener (new MyActionListener ());…

class MyActionListener implements ActionListener{

public void actionPerformed (ActionEvent e){

if (e.getActionCommand().equals("disable")) {b2.setEnabled(false);b1.setEnabled(false);b3.setEnabled(true);

} else { b2.setEnabled(true);b1.setEnabled(true);b3.setEnabled(false);

}}

}

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 14

Toggle buttons

• JToggleButton with subclasses– JCheckBox– JRadioButton

• Three kinds of events

• Checking state

Click press: ChangeEvent // button armedChangeEvent // button pressed

Click release: ChangeEvent // button selectedItemEvent // item state changedChangeEvent // button releasedActionEvent // full button press

if (button.isSelected()) …

good forradio button!

good forcheck box!

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 15

JCheckBox

• Check box: on/off toggle, each boxindependent of all others

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 16

JCheckBox

• ItemListener interface

• Handling events for a JCheckBox…– (next slide)

void itemStateChanged(ItemEvent e) Invoked when an item has been selected or deselected.

Page 5: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 17

CheckBoxListener myListener = new CheckBoxListener(); chinButton.addItemListener(myListener); glassesButton.addItemListener(myListener); hairButton.addItemListener(myListener); teethButton.addItemListener(myListener); ... class CheckBoxListener implements ItemListener { public void itemStateChanged(ItemEvent e) { ... Object source = e.getItemSelectable(); if (source == chinButton) { //...make a note of it... } else if (source == glassesButton) { //...make a note of it... } else ...

if (e.getStateChange() == ItemEvent.DESELECTED) //...make a note of it... picture.setIcon(/* new icon */); } }

JCheckBox

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 18

JRadioButton

• Radio button: on/off toggle, but only one ofa group of buttons can be selected

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 19

JRadioButton birdButton = new JRadioButton(birdString); birdButton.setSelected(true); JRadioButton catButton = new JRadioButton(catString); JRadioButton dogButton = new JRadioButton(dogString); JRadioButton rabbitButton = new JRadioButton(rabbitString); JRadioButton pigButton = new JRadioButton(pigString); …

ButtonGroup group = new ButtonGroup(); group.add(birdButton); group.add(catButton); group.add(dogButton); group.add(rabbitButton); group.add(pigButton); ... << still need to add buttons to frame! >>

JRadioButton

group buttonsto handle selection

oneselected

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 20

• Handling events RadioListener myListener = new RadioListener(); birdButton.addActionListener(myListener); catButton.addActionListener(myListener); dogButton.addActionListener(myListener); rabbitButton.addActionListener(myListener); pigButton.addActionListener(myListener); ... class RadioListener implements ActionListener ... { public void actionPerformed(ActionEvent e) { picture.setIcon(new ImageIcon("images/" + e.getActionCommand() + ".gif")); } }

JRadioButton

Page 6: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 21

Combination (Combo) Box

• Select from a fixed list of items– typically, a not-so-large list– typically, a sorted list (easy to find items)

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 22

JComboBox

String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };

// Create the combo box, select item at index 4 // Indices start at 0, so 4 specifies the pigJComboBox petList = new JComboBox(petStrings);petList.setSelectedIndex(4);…

petList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox) e.getSource(); String petName = (String) cb.getSelectedItem(); picture.setIcon(new ImageIcon("images/" + petName + ".gif")); }});

Note: Listener only neededif you need to do something

for each action!

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 23

Text Field

• Editable, single-line field for typing text

• Keypresses, deletions handled for you!• You can also monitor changes (e.g.,

keypresses) and take action as they happen• Special text fields

– password fields (“•••••”)– validated fields (e.g, “$7.95”)

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 24

JTextField

• Constructors

• Setting / getting text — the obvious...

JTextField() // Constructs a new TextField.JTextField(int columns) // Constructs a new empty TextField with the

specified number of columns.JTextField(String text) // Constructs a new TextField initialized with

the specified text.JTextField(String text, int columns) // Constructs a new TextField initialized with

the specified text and columns.

textField.getText ();textField.setText (text);

Page 7: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 25

• Handling events like usual… … textField.addActionListener(new MyTextListener ()); ... class MyTextListener implements ActionListener ... { public void actionPerformed(ActionEvent e) { String text = textField.getText (); << do something with text… >> } }

JTextField

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 26

Lists

• Storage for a list of items– typically text, or textual

representations of complexobjects (e.g., 9:00pm)

– could also be icons

• Selection– single selection

– single interval

– multiple interval

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 27

List View vs. Data

• Lists have a common interface for dealingwith the sequence of data– allows data to be shared across lists, tables, etc.

• ListModel interface– defines methods for dealing with lists– index in [0, size-1]

Object getElementAt (int index)int getSize ();void addListDataListener (ListDataListener l);

JList(list view)

ListModel(list data)

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 28

JList

• Basic constructor

– sets a basic list model that is unchangeable(no insertions/deletions after creation)

– model created automatically, and you can accessit if you want...

String[] data = {"one", "two", "three", "four"};JList dataList = new JList (data);

for (int i = 0; i < dataList.getModel().getSize(); i++) { System.out.println (dataList.getModel().getElementAt(i));}

Page 8: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 29

JList

• Constructor with more powerful list model– first, create DefaultListModel

• allows insertions/deletions at any time

– then, create JList based on this list model list = new JList (listModel);

listModel = new DefaultListModel();

listModel.addElement (”Thing1"); listModel.addElement (”Thing2"); listModel.addElement (”Thing3"); listModel.addElement (”Thing4"); … listModel.remove (index);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 30

JList

• List selection– complex class ListSelectionModel– handles selection intervals, etc.

• What we’ll need to know… list = new JList (listModel); list.setSelectionMode (ListSelectionModel.SINGLE_SELECTION); <or> (ListSelectionModel.SINGLE_INTERVAL_SELECTION); <or> (ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 31

JList

• Handling selection events (on the JList view) … list.addListSelectionListener (new MyListSelectionListener()); …

public class MyListSelectionListener implements ListSelectionListener { public void valueChanged (ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { if (list.getSelectedIndex() == -1) { // No selection } else { // Selection, update text field. } } } }

// What you might use in the above functions…listModel.addElement (…);listModel.insertElementAt (…);listModel.remove (…);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 32

Tables

• Close cousins to our good friends, Lists• Typical case

– two-dimensional grid• uneditable to display

tabular information• editable to manage

tabular information

– usually alpha-numeric text

• But many possibilities...

Page 9: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 33

Object[][] data = { {"Mary", "Campione", "Snowboarding", new Integer(5), new Boolean(false)}, {"Alison", "Huml", "Rowing", new Integer(3), new Boolean(true)}, {"Kathy", "Walrath", "Chasing toddlers", new Integer(2), new Boolean(false)}, {"Mark", "Andrews", "Speed reading", new Integer(20), new Boolean(true)}, {"Angela", "Lih", "Teaching high school", new Integer(4), new Boolean(false)} }; String[] columnNames = {"First Name”, "Last Name”, "Sport”, "# of Years”, … } JTable table = new JTable(data, columnNames);

Basic table

• Simple example

• Problems: all cells are editable Strings,full array is pre-initialized

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 34

Table model

• As for lists, tables have Model vs. View

• Create model first, then create view withthis model

• Table models typically extendAbstractTableModel (next slide…)

MyTableModel myModel = new MyTableModel(); JTable table = new JTable(myModel);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 35

• TableDemo.java example class MyTableModel extends AbstractTableModel { final String[] columnNames = ...//same as before... final Object[][] data = ...//same as before... public int getColumnCount() { return columnNames.length; } ... public Object getValueAt(int row, int col) { return data[row][col]; } public boolean isCellEditable(int row, int col) { //Note that the data/cell address is constant, //no matter where the cell appears onscreen. if (col < 2) { return false; } else { return true; } } ...

Table model

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 36

Table view

• Resizing columns TableColumn column = null; for (int i = 0; i < 5; i++) { column = table.getColumnModel().getColumn(i); if (i == 2) { column.setPreferredWidth(100); //sport column is bigger } else { column.setPreferredWidth(50); } }

Page 10: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 37

Table cells

• Cell renderer– used to draw all cells, shared by cell type

• Boolean -- rendered with a check box• Number -- rendered by a right-aligned label• ImageIcon -- rendered by a centered label• Object -- rendered by a label w/ the object's string

• Cell editor– takes over when user edits the cell

• Example: Integer object in cell– renderer: JLabel, right-aligned– editor: JTextField, right-aligned

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 38

Table cells

• Different editors in one table

Text Field Combo Box Check Box

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 39

Table cells

• Color chooser as editor

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 40

Table data manager

• Provide way of manipulating data in layerbetween model and view

• One important, common use: Sorting!CLICK!

Page 11: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 41

Trees

• Lots of data fall nicely intoa hierarchy– tree structure: every node

has 1 parent (except root)– e.g., directories & files,

company managementstructures, Swingcomponents!

• Nice to have a convenient,standard way of storingand viewing

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 42

Swing Trees

• Basic structure– root node– branch nodes– leaf nodes

• Yet again… Model vs. View– model = hierarchy of data/information– view = vertical list of currently visible nodes that

can be expanded or collapsed

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 43

Tree model

• Constructing the model– construct root node, as

DefaultMutableTreeNode

– construct other nodes & add to parent node

– finally, construct model with root node

DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series");

category = new DefaultMutableTreeNode ("Books for Java Programmers"); top.add(category); book = new DefaultMutableTreeNode ("The Java Tutorial: Object-Oriented”); category.add(book);

treeModel = new DefaultTreeModel(rootNode);

can beany Object!

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 44

Tree view

• Create a JTree with the model– often good idea to add scrollbars

DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series"); ... << create tree model >> ... JTree tree = new JTree(top); JScrollPane treeView = new JScrollPane(tree);

Page 12: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 45

Tree view

• Selection based on “paths”– path of nodes from root to node (leaf or branch)

– in Swing: TreePath class stores path as array– or, method direct to bottom-most node…

tree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION); ... DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 46

Tree view

• Handling selection events tree.addTreeSelectionListener (new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return;

if (node.isLeaf()) { Object nodeInfo = node.getUserObject(); BookInfo book = (BookInfo)nodeInfo; displayURL(book.bookURL); } else { displayURL(helpURL); } } });

handle branch

handle leaf

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 47

Tree extras

• Changing view properties– node connectors

– different renderers

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 48

Useful things to know

Components To Check/Set State To Handle Events

JButton ActionListener

JCheckBox void setSelected (boolean)boolean isSelected () ItemListener

JRadioButton void setSelected (boolean)boolean isSelected () ActionListener

JComboBox void setSelectedIndex (int)Object getSelectedItem () ActionListener

JSlider void setValue(int)int getValue() ChangeListener

JList void setSelectedIndex (int)int getSelectedIndex () ListSelectionListener

DefaultListModel

void addElement (Object)void insertElementAt (Object,int)void remove (int)Object getElementAt (int)int getSize ()

ListDataListener[created for you if you use JList constructor passing list model]

JTextField void setText (String)String getText () ActionListener

Page 13: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 49

Menus

• A great GUI development! (Apple Lisa)• Fit lots of functionality into a small space

– requires overlapping & restoring of graphics

• Have become more standardized,more hierarchical, & just plain bigger

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 50

Swing Menu Components

• Within the component hierarchy,can contain several types of components

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 51

Menu Bar

• Represents the bar of top-level items• Creating a menu bar

• Setting the bar in a frame, applet, etc.

JMenuBar ()JMenu add (JMenu)

void setJMenuBar(JMenuBar)JMenuBar getJMenuBar()

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 52

Menu

• Any item — in a menu bar or menu — thatdisplays more options

• Creating the menu

• Adding items (options) to the menu

JMenu () JMenu (String)

JMenuItem add (JMenuItem)JMenuItem add (String)void addSeparator ()

JMenuItem insert (JMenuItem, int)void insert (String, int)void insertSeparator(int)

Page 14: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 53

Menu Items

• Terminal components of the menu,with actions associated with them

• Creating menu items (w/ Strings, Icons)

JMenuItem()JMenuItem(S)JMenuItem(I)JMenuItem(S,I)

JCheckBoxMenuItem()JCheckBoxMenuItem(S)JCheckBoxMenuItem(I)JCheckBoxMenuItem(S,I)

JRadioButtonMenuItem()JRadioButtonMenuItem(S)JRadioButtonMenuItem(I)JRadioButtonMenuItem(S,I)

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 54

Menu Items

• How do you handle menu item events?(this is, when the item is selected)

• Remember, menu items are buttons —treat them that way!

• So then…– JMenuItem --> action listener– JRadioButtonMenuItem --> action listener– JCheckBoxMenuItem --> item listener

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 55

Menu Items

• Adding keys to items– Mnemonics : keys that navigate

menus, only visible components

– Accelerators : keys that provideshortcuts directly to function,visible or not

void setAccelerator (KeyStroke)

void setMnemonic (int)

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 56

MenuDemo.java

menuBar = new JMenuBar(); setJMenuBar(menuBar);

menu = new JMenu("A Menu"); menu.setMnemonic(KeyEvent.VK_A); menu.getAccessibleContext().setAccessibleDescription( "The only menu in this program that has menu items"); menuBar.add(menu);

menuItem = new JMenuItem("A text-only menu item", KeyEvent.VK_T); menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_1, ActionEvent.ALT_MASK)); menuItem.getAccessibleContext().setAccessibleDescription( "This doesn't really do anything"); menu.add(menuItem);

menuItem = new JMenuItem("Both text and icon", new ImageIcon("images/middle.gif")); menuItem.setMnemonic(KeyEvent.VK_B); menu.add(menuItem);

create menu bar

create menu,with “A”

mnemonic

moremenuitems

Page 15: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 57

MenuDemo.java

menu.addSeparator();

ButtonGroup group = new ButtonGroup(); rbMenuItem = new JRadioButtonMenuItem ("A radio button menu item"); rbMenuItem.setSelected(true); rbMenuItem.setMnemonic(KeyEvent.VK_R); group.add(rbMenuItem); menu.add(rbMenuItem);

rbMenuItem = new JRadioButtonMenuItem("Another one"); rbMenuItem.setMnemonic(KeyEvent.VK_O); group.add(rbMenuItem); menu.add(rbMenuItem);

menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem ("A check box menu item"); cbMenuItem.setMnemonic(KeyEvent.VK_C); menu.add(cbMenuItem);

add separator

createradio buttonmenu items

w/ button group

createcheck box

menu items

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 58

MenuDemo.java

submenu = new JMenu("A submenu"); submenu.setMnemonic(KeyEvent.VK_S);

menuItem = new JMenuItem("An item in the submenu"); menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_2, ActionEvent.ALT_MASK)); submenu.add(menuItem);

menuItem = new JMenuItem("Another item"); submenu.add(menuItem); menu.add(submenu);

menu = new JMenu("Another Menu"); menu.setMnemonic(KeyEvent.VK_N); menu.getAccessibleContext().setAccessibleDescription( "This menu does nothing"); menuBar.add(menu);

add submenu

add itemsto submenu

add secondmenu in bar(no items!)

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 59

Pop-Up Menus

• Menu that can be brought up anywhere on a“registered” component (frame, button, …)

• Menus actually use pop-ups to show items!

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 60

Menu layout ?!?

• You can even (gasp!) lay out the menu– putting glue in the menu bar

(ok, this I can see)

– changing the layout of the menu bar / items(please don’t try this at home)

Page 16: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 61

Text components

• GUIs may be graphical, but TEXT still formsthe core of many interactions– reading text: help manuals, web pages, …– writing text: word processing, email, …

• Some text comes in short bursts,some comes in long passages

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 62

Swing text components

• Text controls– limited amount of information, then action (?)

• Plain text areas– unformatted text of unlimited length

• Styled text areas– display, edit text of many styles

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 63

Text component components

• What does a text component consist of?– model / document : stores textual content– view : displays text– controller / “editor kit” : implements editing

capabilities for read/write– keymap : binds keys to actions– support for undo/redo, carets

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 64

Text model / document

• Text components = ViewDocument = Model

• The document ...– contains text in logical structure

(paragraphs, styles, etc.)– provides low-level support for editing text with

insert and remove– notifies document & undo listeners of changes– manages position of focus (e.g., cursor)– allows retrieval of text information / properties

Remember lists?

Page 17: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 65

Text editor kit

• Functionality for editing - inserting,deleting, cutting, pasting, …– e.g., move to next word/para/page, select …– stored as Swing “Action”s

• All text components have them,but you can’t always get at them– e.g., text fields

• Built-in Swing editors– DefaultEditorKit : plain text– HTMLEditorKit : HTML– RTFEditorKit : RTF

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 66

Text keymaps

• Associate keys with actions– classes: Keystroke --> Action– e.g., “Cmd-C” --> “copy”

• By default, text components useJTextComponent.DEFAULT_KEYMAP

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 67

Text component example

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 68

Text & password fields

• Text field

• Password field

JTextField textField = new JTextField(10); textField.setActionCommand(textFieldString); textField.addActionListener(this);

public void actionPerformed(ActionEvent e) { String prefix = "You typed \""; if (e.getActionCommand().equals(textFieldString)) { JTextField source = (JTextField)e.getSource(); actionLabel.setText(prefix + source.getText() + "\""); } else { JPasswordField source = (JPasswordField)e.getSource(); actionLabel.setText(prefix + new String(source.getPassword()) + "\""); } }

JPasswordField passwordField = new JPasswordField(10); passwordField.setActionCommand(passwordFieldString); passwordField.addActionListener(this);

Page 18: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 69

Plain text area

• Create & initialize (if desired)

• Set properties (note single font/style)

JTextArea textArea = new JTextArea( "This is an editable JTextArea " + "that has been initialized with the setText method. " + "A text area is a \"plain\" text component, " + "which means that although it can display text " + "in any font, all of the text is in the same font." );

textArea.setFont(new Font("Serif", Font.ITALIC, 16)); textArea.setLineWrap(true); textArea.setWrapStyleWord(true);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 70

Plain text area

• Setting scrollbars– we haven’t really done this yet, but…– use an intermediate-level “scroll pane”

JScrollPane areaScrollPane = new JScrollPane(textArea); areaScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); areaScrollPane.setPreferredSize(new Dimension(250, 250)); areaScrollPane.setBorder(...create border...);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 71

Styled text area

• Creating an uneditable “editor pane” (huh?)linked to a URL page

JEditorPane editorPane = new JEditorPane(); editorPane.setEditable(false); ...//create a URL object for the TextSamplerDemoHelp.html file... try { editorPane.setPage(url); } catch (IOException e) { System.err.println("Attempted to read a bad URL: " + url); }

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 72

Validated text field

• Enforce a particular format on text– e.g., for numbers, dates, times, etc.

• Two types of validation– action-validated : check only on action event

(i.e., user presses Return)– change-validated : check continually, thus never

allowing invalid data

Page 19: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 73

Validated text field

• FormattedTextFieldDemo.javaamountFormat = NumberFormat.getNumberInstance();amountField = new JFormattedTextField(amountFormat);amountField.setValue(new Double(amount));amountField.setColumns(10);

percentFormat = NumberFormat.getNumberInstance();percentFormat.setMinimumFractionDigits (2);rateField = new JFormattedTextField (percentFormat);rateField.setValue(new Double(rate));rateField.setColumns(10);

numPeriodsField = new JFormattedTextField ();numPeriodsField.setValue (new Integer(numPeriods));numPeriodsField.setColumns (10);

paymentFormat = NumberFormat.getCurrencyInstance();paymentField = new JFormattedTextField (paymentFormat);paymentField.setValue (new Double(payment));paymentField.setColumns (10);paymentField.setEditable (false);paymentField.setForeground (Color.red);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 74

Panels

• As we’ve seen…

– don’t really do anything– logical groupings for layouts,

with optional borders / labels

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 75

Panel borders

• Various types of borders

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 76

Panel borders

• Creating with BorderFactory– empty borders (for spacing)

– line border

– other types… etched = BorderFactory.createEtchedBorder(); raisedbevel = BorderFactory.createRaisedBevelBorder(); loweredbevel = BorderFactory.createLoweredBevelBorder(); empty = BorderFactory.createEmptyBorder(); … titledcenter = BorderFactory.createTitledBorder (blackline, "title"); title2.setTitleJustification(TitledBorder.CENTER);

Border blackline = BorderFactory.createLineBorder(Color.black); component.setBorder(blackline);

Border spacer = BorderFactory.createEmptyBorder (top, left, bottom, right); component.setBorder (spacer);

actually,apply to anycomponents!

Page 20: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 77

Scroll panes

• Sometimes, components are too big todisplay in whole

• So add scrollbars!

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 78

JScrollPane

• Constructors

• Scrollbar policies

• Note: typically don’t create scrollbars andviewport — all taken care of!

JScrollPane(Component view)JScrollPane(Component view, int vsbPolicy, int hsbPolicy)

HORIZONTAL_SCROLLBAR_AS_NEEDED HORIZONTAL_SCROLLBAR_ALWAYS HORIZONTAL_SCROLLBAR_NEVER

VERTICAL_SCROLLBAR_AS_NEEDED VERTICAL_SCROLLBAR_ALWAYS VERTICAL_SCROLLBAR_NEVER

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 79

Scroll pane features

• Customizing row/column headers

SwingRule

components

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 80

Scroll pane features

• Being “scrolling-savvy”– must implement Scrollable interface

getScrollableBlockIncrement getScrollableUnitIncrement getPreferredScrollableViewportSize getScrollableTracksViewportHeight getScrollableTracksViewportWidth

e.g.lists

tablestreestext

Page 21: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 81

Split panes

• Two related panes, limited screen area

– often, one panefor selecting,second pane forviewing selection

– often, both panesare scroll panes

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 82

JSplitPane

• Example splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScrollPane, pictureScrollPane); splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(150);

(Be afraid. Be very afraid.)

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 83

Split pane nesting

• Can create hierarchical split panes,just like all panels

(Ok, better.)

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 84

Tabbed panes

• Panes that sharethe same space– panes components

appear, disappearwith selection

• Each pane has alogical groupingof functions– lots of functions– small space

Page 22: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 85

JTabbedPane

• Example

• Similar in functionality to card layout

ImageIcon icon = new ImageIcon("images/middle.gif"); JTabbedPane tabbedPane = new JTabbedPane(); Component panel1 = makeTextPanel("Blah"); tabbedPane.addTab("One", icon, panel1, "Does nothing"); tabbedPane.setSelectedIndex(0); Component panel2 = makeTextPanel("Blah blah"); tabbedPane.addTab("Two", icon, panel2, "Does twice as much nothing"); ...

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 86

Toolbars

• Provide quick & easyaccess to functions– often implement same

functions as menus– often are buttons,

but don’t have to be– often have iconic

representations

• Flexible layoutand positioning– attached vs. floating

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 87

JToolBar

• Construct toolbar

• Create panel with BorderLayout• Add main panel to center,

toolbar to one of outside areas

JToolBar toolBar = new JToolBar(); button = new JButton(new ImageIcon("images/left.gif")); toolBar.add(button); button = new JButton(new ImageIcon("images/middle.gif")); toolBar.add(button); ...

contentPane.setLayout(new BorderLayout()); contentPane.add(toolBar, BorderLayout.NORTH); contentPane.add(scrollPane, BorderLayout.CENTER);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 88

JToolBar

• Swing handles the rest!– user can drag toolbar to other BorderLayout area

– user can drag toolbar out to create floating bar

toolBar.setFloatable (true);

Page 23: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 89

Toolbars with shared actions

• Swing Action class– define Action, assign to multiple components

• e.g., assign “Paste” to menu item and toolbar button

– features of an Action• text and icon• action listener• various other associated states

– why bother with an Action?• single action listener for all components• centralized text, icon• centralized “enabled” state, tool tip, etc.

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 90

Toolbars with shared actions

• Action example leftAction = new AbstractAction("Go left", new ImageIcon("images/left.gif")) { public void actionPerformed(ActionEvent e) { displayResult("Action for first button/menu item", e); } }; button = toolBar.add (leftAction); button.setText (""); // an icon-only button button.setToolTipText ("This is the left button"); menuItem = mainMenu.add (leftAction); menuItem.setIcon (null); // arbitrarily, no icon in menu …

leftAction.setEnabled (selected);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 91

Internal frames / windows

• Provides one way to open multiple frameswithin a single parent frame– design advantages? disadvantages?

iconified

normal

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 92

JInternalFrame

• Construct internal frame

• Create desktop for main frame,add internal frame

InternalFrame intFrame = new InternalFrame(); //...Create the GUI and put it in the frame... //...Then set the window size or call pack... //...and set the window's location. intFrame.setLocation (xOffset*openFrameCount, yOffset*openFrameCount); intFrame.setVisible (true);

desktop = new JDesktopPane(); desktop.add (intFrame); frame.setContentPane (desktop); ... desktop.setDragMode (JDesktopPane.OUTLINE_DRAG_MODE); //1.3 code

Page 24: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 93

Dialogs

• Dependent on a frame — if parent framedies, so does the dialog

• Two basic types– modal: blocks all

other user input• errors, alerts, …

– non-modal: canstill interact withmain frame

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 94

JDialog

• For non-modal (modeless) dialogs, mustcreate JDialog directly and build frames

• But for your typical modal dialog uses,Swing’s built-in dialogs will do fine

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 95

JOptionPane

• Useful standard modal dialog

question information

warning errorJOptionPane.showMessageDialog (frame, "Eggs aren't supposed to be green.");

int n = JOptionPane.showConfirmDialog( frame, "Would you like green eggs and ham?", "An Inane Question", JOptionPane.YES_NO_OPTION);

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 96

Overall program structure

• One good style to follow...public class MyWindow extends JFrame {

<< instance variables for our window frame >>

MyWindow () {super (<<name>>);<< create all components and add to frame >>

}

class <<MyListener>> implements <<ListenerInterface>> { … }class <<MyListener>> implements <<ListenerInterface>> { … }…

public static void main(String s[]) {JFrame frame = new MyWindow ();<< add frame listeners >><< finish and display frame >>

}}

Page 25: Pageumpeysak/Classes/GUI/lectures/cs338-l4… · Page ‹#› CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 5 Buttons •AbstractButton = abstract parent class

Page ‹#›

CS 338: Graphical User Interfaces. Dario Salvucci, Drexel University. 97

Finally!

• We’re done the Swing components!Or at least the ones we’ll be looking at.

• Still ones we haven’t discussed, like …– JApplet top-level container– JLayeredPane intermediate container– etc.

• Make use of Sun’s Java Swing web siteand any of numerous Java & Swing books