intro to swing

140
Intro to Swing GUI development

Upload: thad

Post on 19-Mar-2016

49 views

Category:

Documents


0 download

DESCRIPTION

Intro to Swing. GUI development. Swing is. A big API Built on AWT (another big API) Used for GUI's. Swing class hierarchy fragment. Component. AWT. Swing. Container. JComponent. Window. Panel. JWindow. Dialog. Frame. JFrame. JDialog. JTree. JPanel. JLabel. JTable. JApplet. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Intro to Swing

Intro to Swing

GUI development

Page 2: Intro to Swing

Swing is

• A big API• Built on AWT (another big API)• Used for GUI's

Page 3: Intro to Swing

Component

Container

Panel Window JComponent

JApplet

Frame JWindowDialog

JFrame JDialog

JLabel JPanel JTable JTree

Swing class hierarchy fragmentAWT

Swing

Page 4: Intro to Swing

Other basic classes

• AWT classes defined in the package java.awt– Color, ( an immutable class)– Point, – Dimension, – Font

Page 5: Intro to Swing

JOptionPane Examples

Page 6: Intro to Swing

JComboBox A JComboBox looks like a text field with an

arrow next to it. If you click on the arrow, the list of possible values is displayed.

If the Jcombobox is set to be editable, then you can edit the current selection as if it was a text field.

Only one item can be selected at a time. You can retrieve it by calling: getSelectedItem method.

Add the choice items to the end of the list with the addItem method.

Page 7: Intro to Swing

Progress Bar

• Displays progress of operation– Can be used like a gauge

• Usage:– Initialize

JProgressBar progressBar = new JProgressBar();progressBar.setMinimum(0);progressBar.setMaximum(numberSubOperations);

– GoprogressBar.setValue(progressBar.getMinimum());for (int i = 0; i < numberSubOperations; i++) { progressBar.setValue(i); performSubOperation(i);}

Page 8: Intro to Swing

Intro to The Progress Dialog

Dynamic Feedback

Page 9: Intro to Swing

Why Dynamic Feedback?

• Users interact more smoothly with your application if you keep them informed about the application's state.

– Progress animation--an indicator such as a progress bar that shows what percentage of an operation is complete

Page 10: Intro to Swing

When?

• Use a progress bar whenever users are blocked from interacting with the application for more than 6 seconds.

Page 11: Intro to Swing

Use• Users cannot interact with a progress bar.•  Update the progress bar to show the proportion

completed at least every 4 seconds.• If you overestimate how much is already done,

the progress bar can remain at 99 percent until the task is complete.

• If you underestimate how much is already done, fill the remaining portion of the progress bar when the operation completes.

• The percentage done should never decrease.

Page 12: Intro to Swing

Component

Container

Panel Window JComponent

JApplet

Frame JWindowDialog

JFrame JDialog

JLabel JPanel JTable JTree

Swing class hierarchy fragmentAWT

Swing

Page 13: Intro to Swing

Progress Bar

• Displays progress of operation– Can be used like a gauge

• Usage:– Initialize

JProgressBar progressBar = new JProgressBar();progressBar.setMinimum(0);progressBar.setMaximum(numberSubOperations);

– GoprogressBar.setValue(progressBar.getMinimum());for (int i = 0; i < numberSubOperations; i++) { progressBar.setValue(i); performSubOperation(i);}

Page 14: Intro to Swing

JProgressBar Methods

javax.swing.JProgressBar +JProgressBar() +JProgressBar(min: int, max: int) +JProgressBar(orient: int) +JProgressBar(orient: int, min: int,

max: int) +getMaximum(): int +setMaximum(n: int): void +getMinimum(): int +setMinimum(n: int): void +getOrientation(): int +setOrientation(orient: int): void +getPercentComplete():double +getValus(): int +setValus(n: int): void +getString(): String +setString(s: String): void +isStringPainted(): Boolean +setStringPainted(b: boolean): void

Creates a horizontal progress bar with min 0 and max 100. Creates a horizontal progress bar with specified min and max. Creates a progress bar with min 0 and max 100 and a specified orientation. Creates a progress bar with a specified orientation, min, and max.

Gets the maximum value. (default: 100) Sets a new maximum value. Gets the minimum value. (default: 0) Sets a new minimum value. Gets the orientation value. (default: HORIZONTAL) Sets a new minimum value. Returns the percent complete for the progress bar. 0 <= a value <= 1.0. Returns the progress bar's current value Sets the progress bar's current value. Returns the current value of the progress string. Sets the value of the progress string. Returns the value of the stringPainted property. Sets the value of the stringPainted property, which determines whether the

progress bar should render a progress percentage string. (default: false)

javax.swing.JComponent

Page 15: Intro to Swing

Example: JProgressBar DemoObjective: Write a GUI application that lets you copy files. A progress bar is used to show the progress of the copying operation.

CopyFile Run

Page 16: Intro to Swing

• Menu related classes

Basic Controls

Page 17: Intro to Swing

The Components

• A subclass of the java.awt.Component class is called a Component

• A Component has a size, color, etc.• A Component can normally be painted.• When a component is painted it is visible

on the screen.

Page 18: Intro to Swing

Component Subclasses

• Container extends Component• Button extends Component• Window extends Container• Frame extends a Window• Dialog extends a Window• Panel extends a Container• Applet extends a Panel, etc.

Page 19: Intro to Swing

Swing and AWT

• Swing is built on JComponent.• JComponent extends Component• JLabel, JButton, JCheckbox, etc all extend

JComponent• Why?

Page 20: Intro to Swing

Why does JComponent extend Component?

• Swing uses LightWeight Components!• AWT uses HeavyWeight components!• What is the difference?• What is so good about a LightWeight

Component?• What are the drawbacks?

Page 21: Intro to Swing

Do I still need AWT when using Swing?

• Yes!• AWT has many useful tools.• Taken together they form a Framework.

Page 22: Intro to Swing

Basic components to gather input

• JButton• JCheckBox a toggled on/off button displaying state

to user.

• JRadioButton a toggled on/off button displaying its state to user.

Page 23: Intro to Swing

basic components

• JComboBox a drop-down list with optional editable text field. The user can key in a value or select a value from drop-down list.

• Jlist allows a user to select one or more items from a list.

• Jmenu popup list of items from which the user can select.

• Jslider lets user select a value by sliding a knob.

• JTextField area for entering a single line of input.

Page 24: Intro to Swing

Basic components to present information

• JLabel contains text string, an image, or both.

• JProgressBar communicates progress of some work.

• JToolTip describes purpose of another component.

• JTree a component that displays hierarchical data in outline form.

• JTable a component user to edit and display data in a two-dimensional grid.

• JTextArea, JTextPane, JEditorPane

– define multi-line areas for displaying, entering, and editing text.

Page 25: Intro to Swing

Swing components

Page 26: Intro to Swing

Container• Component that can contain other components and containers.

has

JComponent

Component

Container

Page 27: Intro to Swing

Intermediate components

• Used to organize and position other components. – JPanel container of components.

– JScrollPane panel with scrollbars.

– JSplitPane divides two components graphically.

– JTabbedPane lets the user switch between a group of components by clicking on a labeled tab;

– JToolBar used for displaying a set of commonly used controls.

Page 28: Intro to Swing

Example of component organization

• Wherever this panel is used, it will present the two buttons.

The following creates a JPanel and adds two buttons, labeled “on” and “off.”

JPanel p = new JPanel();p.add(new JButton("on"));p.add(new JButton("off"));

Page 29: Intro to Swing

Getting the screen size

public static Dimension getSize() {

Toolkit t = Toolkit.getDefaultToolkit();

return t.getScreenSize();

}

Page 30: Intro to Swing

An example of AWT usagepublic class Screen {

public static int getDpi() {

Toolkit t =

Toolkit.getDefaultToolkit();

return t.getScreenResolution();

}

Page 31: Intro to Swing

Top-level container• It’s not contained in any other container.

• provide screen area where other components can display themselves. – JApplet, JDialog, JFrame, and JWindow are

commonly used as top-level containers.

Page 32: Intro to Swing

JFrame• It’s a window with title, border, (optional)

menu bar and user-specified components.• It can be moved, resized, iconified.• It is not a subclass of JComponent. • Delegates responsibility of managing user-

specified components to a content pane, an instance of JPanel.

Page 33: Intro to Swing

Jframe

Jframe internal structure

Jframe

Page 34: Intro to Swing

JFrame• To add a component to a JFrame, add it to the content pane:

JFrame f = new JFrame("A Frame");JButton b = new JButton("Press");Container cp = f.getContentPane();cp.add(b)

Page 35: Intro to Swing

JFrame components are in its content pane.

JFramecontent pane

Container

Component

Page 36: Intro to Swing

Swing vs AWT

• Swing has lightweight components

• Light weight components have no peers

• Look and feel variations available

• Swing is SLOW

• AWT is heavyweight • heavyweight comps

require peers.• Always looks like the

platform it runs on.• AWT is FAST

Page 37: Intro to Swing

Simple Output, a message dialog

public static void messageDialog(Object o) {

JOptionPane.showMessageDialog(null, o);

}

Page 38: Intro to Swing

Simple Input

public class In {

public static String getString(Object o) {

return JOptionPane.showInputDialog(o);

}

How do we get an int?

Page 39: Intro to Swing

Getting an Int

public static int getInt(Object o) {

return Integer.parseInt(

getString(o));

}

Page 40: Intro to Swing

JList

– a component that allows a user to select one or more elements from a listString[] data = {"one", "two", ...}; JList list = new JList(data);

Page 41: Intro to Swing

JList– requires a ListSelectionListener that implements

public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { //selected: list.getSelectedValue() }}

– selection mode can be set to single, single interval, or multiple interval

• list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

Page 42: Intro to Swing

Lists can be dynamic

– suppose you want the list to change during execution of the program

– use a ListModel (normally DefaultListModel) to contain the data

Page 43: Intro to Swing

dynamic jlist

– create the list and pass in the ListModel as input– add or remove elements in the ListModel– the GUI will update the list dynamically

DefaultListModel listModel = new DefaultListModel();

JList list = new JList(listModel);listModel.addElement(object);listModel.removeElement(i);

Page 44: Intro to Swing

Scroll Panes

– sometimes the list will be too long to display in the GUI

– Solution: display the list inside a JScrollPane• create a scroll pane containing the list• state how many rows you want to display• display the scroll pane, not the list• everything else is as before

Page 45: Intro to Swing

jsp

JScrollPane sp = new JScrollPane(list);

list.setVisibleRowCount(5);add(sp);

Page 46: Intro to Swing

Atomic IO

• Atomic actions happen all at once.• Event driven call-backs can complicate

code.• EmployeeRecord = getEmployeeRecord();• How is getEmployeeRecord implemented?

Page 47: Intro to Swing

JDialog

• Used to create custom dialog windows.

Page 48: Intro to Swing

A Jdialog

– a top-level window. – has an owner, generally a frame. – It delegates component management to a

content pane, to which components are added.– It’s displayed by invoking its setVisible

method with an argument of true, and is hidden by invoking its setVisible method with an argument of false

Page 49: Intro to Swing

JDialog• A typical constructor is specified as follows:

public JDialog (Frame owner, String title,boolean modal)

Provides an object to create custom views to get or present data.

Page 50: Intro to Swing

Implementing getXXX

• get data – – from a file– from the web– from the user– from …

• Hiding how the data is obtain encapuslates complexity.

Page 51: Intro to Swing

JColorChooser dialogs• JColorChooser presents a pane of controls that allow a user to select

and manipulate a color.

Page 52: Intro to Swing

Error Control

• int I = getInt(“enter an int [1..10]”,1,10);• The getInt function protects the range on

the int. If the value is not correct, we prompt the user again.

• The RHS waits for the assignment to complete

Page 53: Intro to Swing

JFileChooser• Swing provides a file chooser implemented in 100% pure Java

• JFileChooser contains a method for displaying the chooser within a dialogJFileChooser f = new JFileChooser();if ( f.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION )

{File file = f.getSelectedFile();

}

• The JFileChooser can display open, save and custom dialogs– showOpenDialog (JComponent)– showSaveDialog (JComponent)– showDialog (JComponent,

String)

• JFileChooser allows multiple files to be selected by setting the MuliSelectionEnabled property to true– setMultiSelectionEnabled(tr

ue);

Page 54: Intro to Swing

FileChooserJFileChooser directory = new JFileChooser();directory.setCurrentDirectory(new File(“.”));directory.showOpenDialog(this); //open dialogFile file = directory.getSelectedFile();

Page 55: Intro to Swing

JFileChooser.getSelectedFiles

• JFileChooser.getSelectedFiles can be called to get an array of the selected files– File[] files = f.getSelectedFiles();

• The JFileChooser abstracts the file view from the chooser using the javax.swing.filechooser.JFileView abstract class

• You can write your own file view by subclassing JFileView and passing it to the JFileChooser– f.setFileView (new ImageFileView());

• One method of the JFileView returns an icon• This can be overridden to display different icons for different types of files in the

chooser

Page 56: Intro to Swing

But how do you select a directory?

• Can JFileChooser select a directory?• What about JTree?

Page 57: Intro to Swing

Get a Directory

Page 58: Intro to Swing

A Directory Chooser

public static File getReadDirFile(String prompt) {

String dir = DirectoryChooser.getDirectory(prompt);

if (dir==null) return null; File f = new File(dir); return f; }

Page 59: Intro to Swing

Layouts

• What is a layout manager?• What does a layout manager do?• What does a layout manager need?• Why do I need layouts?• Can I do GUI's without layouts?• Can you name a few layouts?

Page 60: Intro to Swing

Some simple layouts

• FlowLayout• GridLayout• BorderLayout• BoxLayout• GridBagLayout….• What are these layouts for?

Page 61: Intro to Swing

Adding Components via Layouts

Page 62: Intro to Swing

Gui.layouts

• DialogLayout

Page 63: Intro to Swing

ParagraphLayout

Page 64: Intro to Swing

Simple ParagraphLayout

Page 65: Intro to Swing

ParagraphLayout• public static void main(String[] args) {• ClosableJFrame cf = new ClosableJFrame();• Container c = cf.getContentPane();• c.setLayout(new ParagraphLayout());• c.add(new JLabel("Name:"));• c.add(new JTextField(20));• c.add(new

JLabel("Name:"),ParagraphLayout.NEW_PARAGRAPH);• c.add(new JTextField(20));• cf.pack();• cf.setVisible(true);• }

Page 66: Intro to Swing

PreferredSizeGridLayout

Page 67: Intro to Swing

GridLayout ignores preferred size

Page 68: Intro to Swing

How do I use PreferredSizeGridLayout?

• public static void PreferredSizeGridLayoutExample() {• JFrame jf = new JFrame();• Container c = jf.getContentPane();• PreferredSizeGridLayout psgl =• new PreferredSizeGridLayout(0, 2, 0, 0);• psgl.setBoundableInterface(new BoundableComponentPlacement());• c.setLayout(psgl);• for (int i = 0; i < 5; i++) {• //rb.setAlignment((int)(Math.random()*8+1));• c.add(new RunButton("ok" + i) {• public void run() {• }• });• c.add(new RunButton("Cancel" + i) {• public void run() {• }• });• }• jf.setSize(200, 200);• jf.setVisible(true);• }

Page 69: Intro to Swing

The following line switches automatically to GridLayout

• psgl.setBoundableInterface(new BoundableComponentPlacement());

Page 70: Intro to Swing

PreferredSize

• Call:• Dimension getPreferredSize(){…}• To get the preferred size of any component.

Page 71: Intro to Swing

VerticalFlowLayout

Page 72: Intro to Swing

What is a layout manager?

• Responsible for positioning and resizing components.

• LayoutManager is an interface that resides in the java.awt.

Page 73: Intro to Swing

Why do I need a Layout Manager?

• You don't need a LayoutManager.• You can set the Layout to null.• You can reposition and resize all

components your self.

Page 74: Intro to Swing

Why is a LayoutManager useful?

• Saves labor?• Keeps the layout resolution versatile.• keeps the interface flexible.

Page 75: Intro to Swing

How does a LayoutManger work?

• Every layout manager works differently.– Typically, they get components dimensions– components dimensions are used to properly

size and place the components.Components implement:Dimension getMinimumSize();Dimension getMaximumSize();Dimension getPreferredSize();

Page 76: Intro to Swing

What if you don't like your LayoutManager?

• Write your own!• GridLayout ignores the min and max and

preferred sizes! It takes the available space and evenly divides it among all the components.

• All components are grown to the available space.

Page 77: Intro to Swing

GridLayout

Page 78: Intro to Swing

FlowLayout

Page 79: Intro to Swing

BoxLayout

keeps min and max size correct. Also centers alignment

Page 80: Intro to Swing

Options passed to the constructor

• X_AXIS - Components are laid out horizontally from left to right.

• Y_AXIS - Components are laid out vertically from top to bottom.

Page 81: Intro to Swing

Custom layout managers (1)

• Ensure no existing manager does the job– GridBagLayout / BoxLayout– Layout manager downloads

Page 82: Intro to Swing

Custom layout managers (2)• Create class which implements Layout Manager interface

– e.g. public class myManager implements LayoutManager

• Must have 5 methods required by interface– void addLayoutComponent(String, Component)– void removeLayoutComponent(Component)– Dimension preferredLayoutSize(Container)– Dimension minimumLayoutSize(Container)– Void layoutContainer(Container)

• See below URL for more documentation– http://java.sun.com/docs/books/tutorial/uiswing/layout/custom.html

Page 83: Intro to Swing

How do I combine GridLayout with Preferred Size?

• I want a fixed number of rows or columns.• I want to use the preferred size of each

component.• I want to resize the components only if I

don't have enough room.• I don't want components to fill all available

space.

Page 84: Intro to Swing

Make your own LayoutManager!

• PreferredSizeGridLayout!

Page 85: Intro to Swing

Using a custom layout manager• public static void main(String[] args) {• ClosableJFrame cj = new ClosableJFrame();• Container c = cj.getContentPane();• c.setLayout(new VerticalFlowLayout(0,5));• for (int j = 0; j < 30; j++)• for (int i = 0; i < 10; i++) {• c.add(new RunLabel("Test#" + j + "," + i) {

• public void run() {• System.out.println(getText());• }• });• }• cj.setSize(200, 200);• cj.show();• }

Page 86: Intro to Swing

Vertical Flow

Page 87: Intro to Swing

Building An AddressBook Index

Page 88: Intro to Swing

JTree

Page 89: Intro to Swing

JTree Example

Page 90: Intro to Swing

JTree

• A tree is a set of hierarchical nodes.• The top of this hierarchy is called “root”.• An element that does not have children is

called “leaf”.• JTree nodes are managed by a “TreeModel”.• “TreeCellRenderer” converts an object to its

visual representation in the tree.

Page 91: Intro to Swing

TreeModel

• Hierarchical data• Parents• Children• Siblings• Ancestors• Descendents

Page 92: Intro to Swing

TreeModel• Object getRoot()• Object getChild(Object parent, int index)• int getChildCount(Object parent)• boolean isLeaf(Object node)• void valueForPathChanged(TreePath path, Object newVal)• int getIndexOfChild(Object parent, Object child) • void addTreeModelListener(TreeModelListener l)• void removeTreeModelListener(TreeModelListener l)

Page 93: Intro to Swing

JTree constructors

• JTree()• JTree(Object[] value)• JTree(Vector value)• JTree(Hashtable value)• JTree(TreeNode root)• JTree(TreeNode root, boolean

asksAllowsChildren)• JTree(TreeModel newModel)

Page 94: Intro to Swing

TreeNodes• Default tree model uses objects of TreeNode to represent the nodes in

the tree.• A default implementation of it is DefaultMutableTreeNode.• TreeNode methods

– TreeNode getChildAt(int childIndex)– int getChildCount()– TreeNode getParent()– int getIndex(TreeNode node)– boolean getAllowsChildren()– boolean isLeaf()– Enumeration children()

• DefaultMutableTreeNode constructors– DefaultMutableTreeNode()– DefaultMutableTreeNode(Object userObject)– DefaultMutableTreeNode(Object userObject, boolean allowsChildren)

Page 95: Intro to Swing

JTree exampleimport javax.swing.* ;import javax.swing.tree.* ;import java.awt.event.* ;import java.awt.* ;import java.util.* ;public class TreeNodeExample extends JPanel {

public TreeNodeExample() {DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Categories") ;DefaultMutableTreeNode parentNode = new DefaultMutableTreeNode("Metals") ;parentNode.add(new DefaultMutableTreeNode("Gold",false)) ;parentNode.add(new DefaultMutableTreeNode("Silver",false)) ;parentNode.add(new DefaultMutableTreeNode("Bronze",false)) ;parentNode.add(new DefaultMutableTreeNode("Copper",false)) ;parentNode.add(new DefaultMutableTreeNode("Iron",false)) ;parentNode.add(new DefaultMutableTreeNode("Platinium",false)) ;parentNode.add(new DefaultMutableTreeNode("Titanium",false)) ;rootNode.add(parentNode) ;parentNode = new DefaultMutableTreeNode("Companies") ;parentNode.add(new DefaultMutableTreeNode("Paradigm Research",false)) ;parentNode.add(new DefaultMutableTreeNode("JavaSoft",false)) ;parentNode.add(new DefaultMutableTreeNode("Wiley Press",false)) ;rootNode.add(parentNode) ;setLayout(new BorderLayout());add(new JScrollPane(new JTree(rootNode)),"Center") ;

}public Dimension getPreferredSize()

{ return new Dimension(200,120) ; }public static void main(String[]args) {

JFrame frame = new JFrame("Tree Node Example") ;TreeNodeExample panel = new TreeNodeExample() ;frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;frame.getContentPane().add(panel,"Center") ;frame.setSize(panel.getPreferredSize()) ;frame.setVisible(true) ;

}}

Page 96: Intro to Swing

TreeModel Listener

• TreeModelListener methods– void treeNodesChanged(TreeModelEvent e)– void treeNodesInserted(TreeModelEvent e)– void treeNodesRemoved(TreeModelEvent e)– void treeStructureChanged(TreeModelEvent e)

• TreeModelEvent methods– TreePath getTreePath()– Object[] getPath()– Object[] getChildren()– int[] getChildIndices()

Page 97: Intro to Swing

Custom TreeModel Implementation

• Implement interface TreeModel

Page 98: Intro to Swing

Custom Tree Model Exampleimport java.io.* ;import java.util.* ;class FileHolder { File myFile ; Vector children ; public FileHolder(File f) { myFile = f ; } public File getFile() { return myFile ; } public Vector getChildren() { if (myFile.isDirectory() && (children==null)) { int max=0; String list[] ; File curFile ; FileHolder curHolder ; children = new Vector() ; list = myFile.list() ; if (list!=null) max = list.length ; for (int i=0;i<max;++i) { curFile = new File(myFile,list[i]) ; curHolder = new FileHolder(curFile) ; children.addElement(curHolder) ; } } return children ; } public String toString() { return myFile.getName() ; }}

Page 99: Intro to Swing

Custom Tree Model Exampleimport javax.swing.* ;import javax.swing.tree.* ;import javax.swing.event.* ;import java.io.* ;import java.util.* ;class FileSystemTreeModel implements TreeModel { protected FileHolder root ; protected Vector listeners ; public FileSystemTreeModel(File r) { root = new FileHolder(r) ; listeners = new Vector() ; } public Object getRoot() { return root ; } public Object getChild(Object parent, int index) { Object retVal=null ; Vector children ; if (parent instanceof FileHolder) { children = ((FileHolder)parent).getChildren() ; if (children!=null) if (index<children.size()) retVal=children.elementAt(index) ; } return retVal ; } public int getChildCount(Object parent) { int retVal = 0 ; Vector children ; if (parent instanceof FileHolder) { children = ((FileHolder)parent).getChildren() ; if (children!=null) retVal = children.size() ; } return retVal ; }

public boolean isLeaf(Object node) { boolean retVal = true ; File file ; if (node instanceof FileHolder) { file = ((FileHolder)node).getFile() ; retVal = file.isFile() ; } return retVal ; } public void valueForPathChanged(TreePath path, Object newVal) { } public int getIndexOfChild(Object parent, Object child) { int retVal = -1 ; Vector children ; if (parent instanceof FileHolder) { children = ((FileHolder)parent).getChildren() ; if (children!=null) retVal = children.indexOf(child) ; } return retVal ; } public void addTreeModelListener(TreeModelListener l) { if ((l!=null)&&!listeners.contains(l)) listeners.addElement(l) ; } public void removeTreeModelListener(TreeModelListener l) { listeners.removeElement(l) ; }}

Page 100: Intro to Swing

Custom Tree Model Exampleimport javax.swing.* ;import java.awt.event.* ;import java.awt.* ;import java.io.* ;import java.util.* ;public class FileTree extends JPanel { public FileTree(String startPath) { JTree tree = new JTree() ; tree.setModel(new FileSystemTreeModel(new File(startPath))) ; setLayout(new BorderLayout()) ; add(new JScrollPane(tree),"Center") ; } public Dimension getPreferredSize() { return new Dimension(250,200) ; } public static void main(String[]s) { JFrame frame = new JFrame("File Tree Example") ; FileTree panel = new FileTree(s.length>0?s[0]:"/") ; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ; frame.getContentPane().add(panel,"Center") ; frame.setSize(panel.getPreferredSize()) ; frame.setVisible(true) ; }}

Page 101: Intro to Swing

Jtree

Page 102: Intro to Swing

DefaultTreeModel

• Interface TreeModel– Declares methods for representing tree structure

• Class DefaultTreeModel– Default TreeModel implementation

•TreeNode•MutableTreeNode•DefaultMutableTreeNode

Page 103: Intro to Swing

DefaultTreeModel

«interface»MutableTreeNode

«interface»TreeNode

getRoot() : ObjectgetChildCount(in parent : Object) : intgetChild(in parent : Object, in index : int) : ObjectgetIndexOfChild(in parent : Object, in child : Object) : intisLeaf(in node : Object) : booleanvalueForPathChanged(in Parameter1)

«interface»TreeModel

root

1

DefaultMutableTreeNode

0..*

children

1

parent

«interface»RowMapperJTree

model

*

TreeUI

BasicTreeUI

uiDelegate

*

AbstractLayoutCachetreePathMapping

*

FixedHeightLayoutCache VariableHeightLayoutCache

JTree Architecture

Page 104: Intro to Swing

TreePaths (1)lastPathComponent parentPath

Page 105: Intro to Swing

TreePaths (2)

• A child TreePath prevents all of its ancestors from being gc’d

• Used throughout JTree as a unique address for a tree node

• Allows equal() node objects to be used in the same tree

• Some duplicate functionality with the data model– trace node parentage– indent level– higher speed, more memory

Page 106: Intro to Swing

JTree expandedState Cache

• Treepath used as key, value is Boolean• Cache entry is not removed when node is collapsed• Child entry is not removed if parent is collapsed

– JTree "remembers" expansion state of child nodesBoolean.TRUEBoolean.TRUE

Boolean.TRUE

Boolean.TRUE

Page 107: Intro to Swing

JTree Layout Cache• BasicTreeUI treePathMapping table• Position and bounding box info for visible

nodes• VariableHeightLayoutCache

– Is JTree default– Caches all visible nodes

• FixedHeightLayoutCache– Caches only expanded visible nodes– Only enabled if JTree largeModel = true and

rows are explicitly set to a fixed height

Page 108: Intro to Swing

JTree Caching Summaryexpandedstate

previously expanded

variableheight

fixedheight

Page 109: Intro to Swing

Custom Tree Model Exampleimport java.io.* ;import java.util.* ;class FileHolder { File myFile ; Vector children ; public FileHolder(File f) { myFile = f ; } public File getFile() { return myFile ; } public Vector getChildren() { if (myFile.isDirectory() && (children==null)) { int max=0; String list[] ; File curFile ; FileHolder curHolder ; children = new Vector() ; list = myFile.list() ; if (list!=null) max = list.length ; for (int i=0;i<max;++i) { curFile = new File(myFile,list[i]) ; curHolder = new FileHolder(curFile) ; children.addElement(curHolder) ; } } return children ; } public String toString() { return myFile.getName() ; }}

Page 110: Intro to Swing

Custom Tree Model Exampleimport javax.swing.* ;import javax.swing.tree.* ;import javax.swing.event.* ;import java.io.* ;import java.util.* ;class FileSystemTreeModel implements TreeModel { protected FileHolder root ; protected Vector listeners ; public FileSystemTreeModel(File r) { root = new FileHolder(r) ; listeners = new Vector() ; } public Object getRoot() { return root ; } public Object getChild(Object parent, int index) { Object retVal=null ; Vector children ; if (parent instanceof FileHolder) { children = ((FileHolder)parent).getChildren() ; if (children!=null) if (index<children.size()) retVal=children.elementAt(index) ; } return retVal ; } public int getChildCount(Object parent) { int retVal = 0 ; Vector children ; if (parent instanceof FileHolder) { children = ((FileHolder)parent).getChildren() ; if (children!=null) retVal = children.size() ; } return retVal ; }

public boolean isLeaf(Object node) { boolean retVal = true ; File file ; if (node instanceof FileHolder) { file = ((FileHolder)node).getFile() ; retVal = file.isFile() ; } return retVal ; } public void valueForPathChanged(TreePath path, Object newVal) { } public int getIndexOfChild(Object parent, Object child) { int retVal = -1 ; Vector children ; if (parent instanceof FileHolder) { children = ((FileHolder)parent).getChildren() ; if (children!=null) retVal = children.indexOf(child) ; } return retVal ; } public void addTreeModelListener(TreeModelListener l) { if ((l!=null)&&!listeners.contains(l)) listeners.addElement(l) ; } public void removeTreeModelListener(TreeModelListener l) { listeners.removeElement(l) ; }}

Page 111: Intro to Swing

Custom Tree Model Exampleimport javax.swing.* ;import java.awt.event.* ;import java.awt.* ;import java.io.* ;import java.util.* ;public class FileTree extends JPanel { public FileTree(String startPath) { JTree tree = new JTree() ; tree.setModel(new FileSystemTreeModel(new File(startPath))) ; setLayout(new BorderLayout()) ; add(new JScrollPane(tree),"Center") ; } public Dimension getPreferredSize() { return new Dimension(250,200) ; } public static void main(String[]s) { JFrame frame = new JFrame("File Tree Example") ; FileTree panel = new FileTree(s.length>0?s[0]:"/") ; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ; frame.getContentPane().add(panel,"Center") ; frame.setSize(panel.getPreferredSize()) ; frame.setVisible(true) ; }}

Page 112: Intro to Swing

Class: javax.swing.JTableSwing Component

• displays data in table• edit the data

Page 113: Intro to Swing

Why do we need a table?

• The JTable component is useful for presenting information of a tabular nature

Page 114: Intro to Swing

JTable properties

– Column is the basic unit of the Table. – Row collection of columns – Cell the location of data.

Page 115: Intro to Swing

Architecture• MVC (Model-View-Controller)• Model:data of the components.• View:visual representation.• Controller:describe how the component

interacts with user.

Page 116: Intro to Swing

MVC

Model Class

Data AccessorMethods

View Class

Display Methods

Controller Class

Event HandlingMethods

Page 117: Intro to Swing

MVC

• MVC paradigm– Model

• Data storage, no presentation elements– View

• No data storage, presentation elements– Controller like a mediator

• Glue to tie the Model and the view together

Page 118: Intro to Swing

Why use MVC?

• Modular design• Consistency• Complexity hiding

Page 119: Intro to Swing

Constructors:

• JTable( ) - JTable( int rows, int columns )• JTable( Object[ ][ ] rowData, Object[ ] columnNames )• JTable( Vector rowData, Vector columnNames )• JTable( TableModel model )• JTable( TableModel model,

TableColumnModel tcModel )• JTable( TableModel model,

TableColumnModel tcModel, ListSelectionModel lsModel )

Page 120: Intro to Swing

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

};

Page 121: Intro to Swing

String[] columnNames = {

“First Name”,“Last Name”,“Sport”,“# of Years”,“Vegetarian”

};

JTable table = new JTable(data, columnNames);

Page 122: Intro to Swing

Interfaces

• TableColumnModel manages column selection and spacing

• TableModel provides data.

Page 123: Intro to Swing

Events

• TableColumnEvent caused by column model changed.

• TableModelEvent caused by TableModel changed

Page 124: Intro to Swing

Change WidthTableColumn column;for (int i = 0; i < 5; i++){

column = table.getColumnModel().getColumn(i);

if (i == 2)column.setPreferredWidth(100);

elsecolumn.setPreferredWidth(50);

}

Page 125: Intro to Swing

To change column widthsTableColumn column = null; for (int i = 0; i < 5; i++) {

column = table.getColumnModel().getColumn(i); if (i == 2) {

column.setPreferredWidth(100); //second column is bigger} else { column.setPreferredWidth(50);}

}

Page 126: Intro to Swing

Build ModelTableModel tm = new AbstractTableModel(){

public void getColumnCount(){

return columnNames.length;}public void getRowCount(){

return data.length;}public Object getValueAt(int row, int col){

return data[row][col];}public Class getColumnClass(int col){

return getValueAt(0, col).getClass();}

Page 127: Intro to Swing

Put the JTable in a JScrollPane

• This automatically deals space for the header and does the right things!

Page 128: Intro to Swing

Split pane

• Allows user-controlled resizing of two components

• Can move divider programmatically with setDividierLocation– int parameter

• absolute position– float parameter

• percentage

Page 129: Intro to Swing

Tabbed Pane

• Tabbed panel control• Similar to using CardLayout with buttons

for selecting cards• Use addTab to add components/panels

Page 130: Intro to Swing

The JDesktopPane

• Parent JLayeredPane. • Can hold multiple overlapping internal

frames.• Internal frames may be dragged, resized,

iconified. • events handled by DesktopManager.

Page 131: Intro to Swing

JDesktopPane Pro

• more window behavior control over than JFrames.

• Can control minimization, • Can control window look and feel.• Appearance same on all platforms, easily

configurable.

Page 132: Intro to Swing

Cons

• Requires more management. • Can’t just add components without saying

where. • Minimization prefs.

Page 133: Intro to Swing

JDesktopPane and JInternalFrame

• Multiple-document interface– A main window (called the parent window)

contains other windows (called child windows)– Manages several open documents that are being

processed in parallel– Implemented by Swing’s JDesktopPane and JInternalFrame

Page 134: Intro to Swing

Using JInternalFrame• Main constructor

– public JInternalFrame(String title, boolean resizable, boolean closeable, boolean maximizable, boolean iconifiable)

• Other useful methods– moveToFront – moveToBack– setSize (required!)– setLocation (required!)

Page 135: Intro to Swing

Internal Frames: Example Codeimport java.awt.*;import java.awt.event.*;import javax.swing.*;

public class JInternalFrames extends JFrame { public static void main(String[] args) { new JInternalFrames(); }

public JInternalFrames() { super("Multiple Document Interface"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); content.setBackground(Color.white);

Page 136: Intro to Swing

Internal Frames: Example Code (Continued)

JDesktopPane desktop = new JDesktopPane(); desktop.setBackground(Color.white); content.add(desktop, BorderLayout.CENTER); setSize(450, 400); for(int i=0; i<5; i++) { JInternalFrame frame = new JInternalFrame(("Internal Frame " + i), true, true, true, true); frame.setLocation(i*50+10, i*50+10); frame.setSize(200, 150); frame.setBackground(Color.white); frame.setVisible(true); desktop.add(frame); frame.moveToFront(); } setVisible(true); } }

Page 137: Intro to Swing

Internal Frames: Example Output

Page 138: Intro to Swing

Outline• DeskTopTest.java• (2 of 3)

Internal Frames Minimize Maximize Close

Minimized internal frames Position the mouse over any corner of a child window toresize the window (if resizing is allowed).

Page 139: Intro to Swing

Outline• DeskTopTest.java• (3 of 3)

Maximized internal frame

Page 140: Intro to Swing

Extra Fields in JInternalFrame

• closable, closed, desktopIcon, desktopPane, frameIcon, icon, iconifiable, layer, layeredPane, maximizable, maximum, resizable, selected