1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 5: Swing Components.

Slides:



Advertisements
Similar presentations
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
Advertisements

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 17 Creating User Interfaces.
Graphic User Interfaces Layout Managers Event Handling.
1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 16 Creating User Interfaces.
© The McGraw-Hill Companies, 2006 Chapter 18 Advanced graphics programming.
Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: –Events: A user or.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 15 Creating User.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L03 (Chapter 15) Creating.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L04 (Chapter 15) Creating.
1 Creating User Interfaces. 2 Motivations A graphical user interface (GUI) makes a system user-friendly and easy to use. Creating a GUI requires creativity.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Graphic User Interfaces Part 1. Typical GUI Screen from Microsoft Word What GUI “components” can you see? –Menus? Buttons? Labels? What else? –Anything.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Chapter 9: Applets Jim Burns Fall Outline Learn about applets Learn about applets Write an HTML doc to host an applet Write an HTML doc to host.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 8: Layout Management.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 13 Creating User.
CIS 068 Welcome to CIS 083 ! Introduction to GUIs: JAVA Swing.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
MVC and Swing IAT 351 Week 7 Lecture/tutorial Lyn Bartram.
DAT602 Database Application Development Lecture 6 JAVA Swing.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
3461A Readings from the Swing Tutorial. 3461A Overview  The follow is the Table of Contents from the trail “Creating a GUI with JFC/Swing” in the “The.
Java Swing. Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT. In addition to the familiar.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
SWING. AbstractButton Swing Buttons are subclasses of the AbstractButton class, which extends JComponent. Abstract class javax.swing.AbstractButton AbstractButton.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
More GUI CSCE 190 – Java Instructor: Joel Gompert Lecture 8 – July 28, 2004.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Dale Roberts GUI Programming using Java - GUI Components Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 35 MVC and Swing MVC.
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 15 Creating User.
CHAPTER:07 JAVA IDE PROGRAMMING-II Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Getting Input. Text Fields A text field is a box that the user can type in Use the JTextField class JTextField tf1 = new JTextField(15); 15 is the field.
CHAPTER:08 JAVA IDE PROGRAMMING-III Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 – Graphical User Interfaces Java Foundations: Introduction to Programming.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 9: Swing Components.
Creating User Interfaces Chapter 13 CSCI CSCI 1302 – Creating User Interfaces2 Outline Introduction Common Features of Swing GUI Components Buttons.
Software Construction LAB 08 Java Programming with SWING GUI Builder.
Java Programming, Second Edition Chapter Thirteen Understanding Swing Components.
Copyright © Curt Hill More Widgets In Abstract Window Toolbox.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
Computer Science [3] Java Programming II - Laboratory Course Lab 4 -1 : Introduction to Graphical user interface GUI Components Faculty of Engineering.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
 Figure illustrates a hierarchy containing many event classes from the package java.awt.event.  Used with both AWT and Swing components.  Additional.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
1 Lecture 8: User Interface Components with Swing.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
GUIs & Event-Driven Programming Chapter 11 Review.
Graphical User Interface (pronounced "gooey")
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
Chapter 7 Creating User Interfaces
Chapter 13 Creating User Interfaces
Chapter 17 Creating User Interfaces
Chapter 17 Creating User Interfaces
Advanced GUIs and Graphics
Presentation transcript:

1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 5: Swing Components

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Widget Week! 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!

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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 today’s focus

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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…)

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Buttons AbstractButton = abstract parent class – JButton – JCheckBox – JRadioButton – JMenuItem – and more… Side note: AbstractButton is an abstract class, not an interface

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 All Buttons Can contain both text and icon What’s an icon? ImageIcon leftButtonIcon = new ImageIcon ("images/right.gif");

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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);

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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); }

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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.");

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JButton Our old friend... Constructors JButton ()// Creates a plain button, no icon or text JButton (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

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JButton Setting the default button (for “Return” key) getRootPane().setDefaultButton (setButton);

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JButton Using HTML in the button label (Only later versions! >= JDK ) b1 = new Jbutton (" D isable middle button ", leftButtonIcon); b2 = new JButton(" Middle button ", middleButtonIcon); b3 = new JButton(" E nable middle button ", rightButtonIcon);

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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); }

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Toggle buttons JToggleButton with subclasses – JCheckBox – JRadioButton Three kinds of events Checking state Click press:ChangeEvent// button pressed Click release:ChangeEvent// button selected ItemEvent// item state changed ChangeEvent// button released ActionEvent// full button press if (button.isSelected()) … good for radio button! good for check box!

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JCheckBox Check box: on/off toggle, each box independent of all others

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JCheckBox ItemListener interface Handling events for a JCheckBox… – (next slide) void itemStateChanged(ItemEvent e) Invoked when an item has been selected or deselected.

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JRadioButton Radio button: on/off toggle, but only one of a group of buttons can be selected

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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);... > JRadioButton group buttons to handle selection one selected

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Combination (Combo) Box Select from a fixed list of items – typically, a not-so-large list – typically, a sorted list (easy to find items)

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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 pig JComboBox 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 needed if you need to do something for each action!

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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”)

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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);

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Handling events like usual… … textField.addActionListener(new MyTextListener ());... class MyTextListener implements ActionListener... { public void actionPerformed(ActionEvent e) { String text = textField.getText (); > } JTextField

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Sliders Allow selection from a range of discrete options – though look & feel is continuous! Typical parts – slider itself – labels – “tick marks”

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JSlider Constructors Example JSlider() Creates a horizontal slider with the range 0 to 100 and an intitial value of 50. JSlider(int orientation) Creates a slider using the specified orientation with the range 0 to 100 and an initial value of 50. JSlider(int min, int max) Creates a horizontal slider using the specified min and max with an initial value of 50. JSlider(int min, int max, int value) Creates a horizontal slider using the specified min, max and value. JSlider(int orientation, int min, int max, int value) Creates a slider with the specified orientation and the specified mimimum, maximum, and initial values. JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL, 0, 30, FPS_INIT); framesPerSecond.setMajorTickSpacing(10); framesPerSecond.setMinorTickSpacing(1); framesPerSecond.setPaintTicks(true); framesPerSecond.setPaintLabels(true);

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JSlider ChangeListener interface Handling events for a JSlider void stateChanged(ChangeEvent) Called when the listened-to component changes state. framesPerSecond.addChangeListener(new SliderListener()); … class SliderListener implements ChangeListener { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); if (!source.getValueIsAdjusting()) { int fps = (int)source.getValue();... } may or may not want this

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Labels Present text or icons on the screen No actions associated with them

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JLabel Constructors Example JLabel() Creates a JLabel instance with no image and with an empty string for the title. JLabel(Icon image) Creates a JLabel instance with the specified image. JLabel(Icon image, int horizontalAlignment) Creates a JLabel instance with the specified image and horizontal alignment. JLabel(String text) Creates a JLabel instance with the specified text. JLabel(String text, Icon icon, int horizontalAlignment) Creates a JLabel instance with the specified text, image, and horizontal alignment. JLabel(String text, int horizontalAlignment) Creates a JLabel instance with the specified text and horizontal alignment. label1 = new JLabel(“Image and Text”, icon, JLabel.CENTER); label1.setVerticalTextPosition(JLabel.BOTTOM); label1.setHorizontalTextPosition(JLabel.CENTER);

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JLabel Using HTML in labels (Only later versions! >= JDK )

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Tool Tips When user’s mouse pointer pauses over an item, “tool tips” provide further information – implicit assumption: user may be considering this item as an option, but isn’t quite so sure…

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JToolTip You won’t usually deal directly with JToolTip — don’t need to construct, etc. Instead, just create tip text as follows: Works for any JComponent !! 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.");

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Lists Storage for a list of items – typically text, or textual representations of complex objects (e.g., 9:00pm) – could also be icons Selection – single selection – single interval – multiple interval

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 List View vs. Data Lists have a common interface for dealing with 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)

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 JList Basic constructor – sets a basic list model that is unchangeable (no insertions/deletions after creation) – model created automatically, and you can access it 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)); }

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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);

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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); (ListSelectionModel.SINGLE_INTERVAL_SELECTION); (ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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 (…);

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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...

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Table model As for lists, tables have Model vs. View Create model first, then create view with this model Table models typically extend AbstractTableModel (next slide…) MyTableModel myModel = new MyTableModel(); JTable table = new JTable(myModel);

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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); }

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Table cells Different editors in one table Text FieldCombo BoxCheck Box

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Table cells Color chooser as editor

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Table data manager Provide way of manipulating data in layer between model and view One important, common use: Sorting! CLICK!

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Trees Lots of data forms nicely into a hierarchy – tree structure: every node has 1 parent (except root) – e.g., directories & files, company management structures, Swing components! Nice to have a convenient, standard way of storing and viewing

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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 be any Object!

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Tree view Create a JTree with the model – often good idea to add scrollbars DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series");... >... JTree tree = new JTree(top); JScrollPane treeView = new JScrollPane(tree);

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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();

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 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 branchhandle leaf

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Tree extras Changing view properties – node connectors – different renderers

CS480: Graphical User Interfaces. Dario Salvucci, Drexel University.1 Useful things to know ComponentsTo Check/Set StateTo 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