Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
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 Frame JFrame JApplet JComponent Window Panel Dialog JWindow JDialog JLabel JPanel JTable JTree Other basic classes • AWT classes defined in the package java.awt – – – – Color, ( an immutable class) Point, Dimension, Font JOptionPane Examples 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. Progress Bar • Displays progress of operation – Can be used like a gauge • Usage: – Initialize JProgressBar progressBar = new JProgressBar(); progressBar.setMinimum(0); progressBar.setMaximum(numberSubOperations); – Go progressBar.setValue(progressBar.getMinimum()); for (int i = 0; i < numberSubOperations; i++) { progressBar.setValue(i); performSubOperation(i); } Intro to The Progress Dialog Dynamic Feedback 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 When? • Use a progress bar whenever users are blocked from interacting with the application for more than 6 seconds. 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. Swing class hierarchy fragment Component AWT Swing Container Frame JFrame JApplet JComponent Window Panel Dialog JWindow JDialog JLabel JPanel JTable JTree Progress Bar • Displays progress of operation – Can be used like a gauge • Usage: – Initialize JProgressBar progressBar = new JProgressBar(); progressBar.setMinimum(0); progressBar.setMaximum(numberSubOperations); – Go progressBar.setValue(progressBar.getMinimum()); for (int i = 0; i < numberSubOperations; i++) { progressBar.setValue(i); performSubOperation(i); } JProgressBar Methods javax.swing.JComponent javax.swing.JProgressBar +JProgressBar() Creates a horizontal progress bar with min 0 and max 100. +JProgressBar(min: int, max: int) Creates a horizontal progress bar with specified min and max. +JProgressBar(orient: int) Creates a progress bar with min 0 and max 100 and a specified orientation. +JProgressBar(orient: int, min: int, max: int) Creates a progress bar with a specified orientation, min, and max. +getMaximum(): int Gets the maximum value. (default: 100) +setMaximum(n: int): void Sets a new maximum value. +getMinimum(): int Gets the minimum value. (default: 0) +setMinimum(n: int): void Sets a new minimum value. +getOrientation(): int Gets the orientation value. (default: HORIZONTAL) +setOrientation(orient: int): void Sets a new minimum value. +getPercentComplete():double Returns the percent complete for the progress bar. 0 <= a value <= 1.0. +getValus(): int Returns the progress bar's current value +setValus(n: int): void Sets the progress bar's current value. +getString(): String Returns the current value of the progress string. +setString(s: String): void Sets the value of the progress string. +isStringPainted(): Boolean Returns the value of the stringPainted property. +setStringPainted(b: boolean): void Sets the value of the stringPainted property, which determines whether the progress bar should render a progress percentage string. (default: false) Example: JProgressBar Demo Objective: Write a GUI application that lets you copy files. A progress bar is used to show the progress of the copying operation. CopyFile Run Basic Controls • Menu related classes 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. 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. Swing and AWT • Swing is built on JComponent. • JComponent extends Component • JLabel, JButton, JCheckbox, etc all extend JComponent • Why? 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? Do I still need AWT when using Swing? • Yes! • AWT has many useful tools. • Taken together they form a Framework. Basic components to gather input • JButton • JCheckBox a toggled on/off button displaying state to user. • JRadioButton state to user. a toggled on/off button displaying its 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 list. allows a user to select one or more items from a • 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. 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 twodimensional grid. • JTextArea, JTextPane, JEditorPane – define multi-line areas for displaying, entering, and editing text. Swing components Container • Component that can contain other components and containers. Component Container JCom ponent has 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. Example of component organization 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")); • Wherever this panel is used, it will present the two buttons. Getting the screen size public static Dimension getSize() { Toolkit t = Toolkit.getDefaultToolkit(); return t.getScreenSize(); } An example of AWT usage public class Screen { public static int getDpi() { Toolkit t = Toolkit.getDefaultToolkit(); return t.getScreenResolution(); } Top-level container • It’s not contained in any other container. • provide screen area where components can display themselves. other – JApplet, JDialog, JFrame, and JWindow are commonly used as top-level containers. 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 userspecified components to a content pane, an instance of JPanel. Jframe Jframe Jframe internal structure 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) JFrame components are in its content pane. JFrame content pane Container Component 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 Simple Output, a message dialog public static void messageDialog(Object o) { JOptionPane.showMessageDialog(null, o); } Simple Input public class In { public static String getString(Object o) { return JOptionPane.showInputDialog(o); } How do we get an int? Getting an Int public static int getInt(Object o) { return Integer.parseInt( getString(o)); } JList – a component that allows a user to select one or more elements from a list String[] data = {"one", "two", ...}; JList list = new JList(data); 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); 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 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); 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 jsp JScrollPane sp = new JScrollPane(list); list.setVisibleRowCount(5); add(sp); Atomic IO • Atomic actions happen all at once. • Event driven call-backs can complicate code. • EmployeeRecord = getEmployeeRecord(); • How is getEmployeeRecord implemented? JDialog • Used to create custom dialog windows. 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 JDialog • A typical constructor is specified as follows: Provides an object to create custom views to get or present data. public JDialog (Frame owner, String title, boolean modal) Implementing getXXX • get data – – – – – from a file from the web from the user from … • Hiding how the data is obtain encapuslates complexity. JColorChooser dialogs • JColorChooser presents a pane of controls that allow a user to select and manipulate a color. 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 JFileChooser • Swing provides a file chooser implemented in 100% pure Java • 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); FileChooser JFileChooser directory = new JFileChooser(); directory.setCurrentDirectory(new File(“.”)); directory.showOpenDialog(this); //open dialog File file = directory.getSelectedFile(); 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 But how do you select a directory? • Can JFileChooser select a directory? • What about JTree? Get a Directory 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; } 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? Some simple layouts • • • • • • FlowLayout GridLayout BorderLayout BoxLayout GridBagLayout…. What are these layouts for? Adding Components via Layouts Gui.layouts • DialogLayout ParagraphLayout Simple ParagraphLayout 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); } PreferredSizeGridLayout GridLayout ignores preferred size 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); } The following line switches automatically to GridLayout • psgl.setBoundableInterface(new BoundableComponentPlacement()); PreferredSize • Call: • Dimension getPreferredSize(){…} • To get the preferred size of any component. VerticalFlowLayout What is a layout manager? • Responsible for positioning and resizing components. • LayoutManager is an interface that resides in the java.awt. 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. Why is a LayoutManager useful? • Saves labor? • Keeps the layout resolution versatile. • keeps the interface flexible. 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(); 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. GridLayout FlowLayout BoxLayout keeps min and max size correct. Also centers alignment 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. Custom layout managers (1) • Ensure no existing manager does the job – GridBagLayout / BoxLayout – Layout manager downloads 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 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. Make your own LayoutManager! • PreferredSizeGridLayout! 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(); } Vertical Flow Building An AddressBook Index JTree JTree Example 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. TreeModel • Hierarchical data • • • • • Parents Children Siblings Ancestors Descendents 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) JTree constructors • • • • • • JTree() JTree(Object[] value) JTree(Vector value) JTree(Hashtable value) JTree(TreeNode root) JTree(TreeNode root, boolean asksAllowsChildren) • JTree(TreeModel newModel) 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) JTree example import 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) ; } } 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() Custom TreeModel Implementation • Implement interface TreeModel Custom Tree Model Example import 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() ; } } Custom Tree Model Example import 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) ; } } Custom Tree Model Example import 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) ; } } Jtree DefaultTreeModel • Interface TreeModel – Declares methods for representing tree structure • Class DefaultTreeModel – Default TreeModel implementation • TreeNode • MutableTreeNode • DefaultMutableTreeNode JTree Architecture «interface» TreeModel getRoot() : Object getChildCount(in parent : Object) : int getChild(in parent : Object, in index : int) : Object getIndexOfChild(in parent : Object, in child : Object) : int isLeaf(in node : Object) : boolean valueForPathChanged(in Parameter1) model uiDelegate JTree TreeUI * «interface» RowMapper * BasicTreeUI 1 «interface» TreeNode DefaultTreeModel root treePathMapping AbstractLayoutCache 1 * «interface» MutableTreeNode 0..* FixedHeightLayoutCache DefaultMutableTreeNode children parent VariableHeightLayoutCache TreePaths (1) lastPathComponent parentPath 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 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 Boolean.TRUE – JTree "remembers" expansion state of child nodes Boolean.TRUE Boolean.TRUE Boolean.TRUE 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 JTree Caching Summary expanded state previously expanded fixed height variable height Custom Tree Model Example import 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() ; } } Custom Tree Model Example import 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) ; } } Custom Tree Model Example import 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) ; } } Class: javax.swing.JTable Swing Component • displays data in table • edit the data Why do we need a table? • The JTable component is useful for presenting information of a tabular nature JTable properties – Column is the basic unit of the Table. – Row collection of columns – Cell the location of data. Architecture • • • • MVC (Model-View-Controller) Model:data of the components. View:visual representation. Controller:describe how the component interacts with user. MVC Model Class View Class Data Accessor Methods Display Methods Controller Class Event Handling Methods 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 Why use MVC? • Modular design • Consistency • Complexity hiding 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 ) 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”, “Vegetarian” }; JTable table = new JTable(data, columnNames); Interfaces • TableColumnModel manages column selection and spacing • TableModel provides data. Events • TableColumnEvent caused by column model changed. • TableModelEvent caused by TableModel changed Change Width TableColumn column; for (int i = 0; i < 5; i++) { column = table.getColumnModel().getColumn(i); if (i == 2) column.setPreferredWidth(100); else column.setPreferredWidth(50); } To change column widths TableColumn 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); } } Build Model TableModel 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(); } Put the JTable in a JScrollPane • This automatically deals space for the header and does the right things! Split pane • Allows user-controlled resizing of two components • Can move divider programmatically with setDividierLocation – int parameter • absolute position – float parameter • percentage Tabbed Pane • Tabbed panel control • Similar to using CardLayout with buttons for selecting cards • Use addTab to add components/panels The JDesktopPane • Parent JLayeredPane. • Can hold multiple overlapping internal frames. • Internal frames may be dragged, resized, iconified. • events handled by DesktopManager. 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. Cons • Requires more management. • Can’t just add components without saying where. • Minimization prefs. 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 Using JInternalFrame • Main constructor – public JInternalFrame(String title, boolean resizable, boolean closeable, boolean maximizable, boolean iconifiable) • Other useful methods – moveToFront – moveToBack Internal Frames: Example Code import 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(); 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); Internal Frames: Example Output Internal Frames Minimize Maximize Close Outline • DeskTo pTest.ja va • (2 of 3) Minimized internal frames Position the mouse over any corner of a child window to resize the window (if resizing is allowed). Maximized internal frame Outline • DeskTo pTest.ja va • (3 of 3) Extra Fields in JInternalFrame • closable, closed, desktopIcon, desktopPane, frameIcon, icon, iconifiable, layer, layeredPane, maximizable, maximum, resizable, selected