Copyright 2003 Mudra Serv ices 1 SWING - JTabbedPane Helps stack pages of information into a single point of reference If information cannot be laid out in one page, it can be split into multiple tabs Not available in AWT But somewhat similar to CardLayout A lot of text editors use it to show open files. Can work with multiple files simultaneously.
122
Embed
Copyright 2003 Mudra Services1 SWING - JTabbedPane Helps stack pages of information into a single point of reference If information cannot be laid out.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Copyright 2003 Mudra Services
1
SWING - JTabbedPane
Helps stack pages of information into a single point of reference
If information cannot be laid out in one page, it can be split into multiple tabs
Not available in AWT But somewhat similar to CardLayout
A lot of text editors use it to show open files. Can work with multiple files simultaneously.
// add the panels to the pane pane.addTab("Name",panel1); pane.addTab("Address",panel2); pane.addTab("Other",panel3); pane.setSelectedComponent(panel1);
// create panel 3 private JPanel createPanel3() { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS)); panel.setBorder(BorderFactory.createEtchedBorder()); panel.add(new JCheckBox("Check if you are still in school")); panel.add(new JCheckBox("Check if you have no medical
problems")); return(panel); }
Copyright 2003 Mudra Services
10
SWING - JTabbedPane
// create main program public static void main(String[] args) { TabbedExample tabbedExample = new
Control the size of scroll bars // changing the size of the scroll bars JScrollBar vBar = pane.getVerticalScrollBar(); Dimension dim = vBar.getSize(); dim.width = 5; vBar.setPreferredSize(dim);
Copyright 2003 Mudra Services
17
SWING - JScrollPane
Unit Increment Block Increment The increment size can be changed from
the default by using the Scrollable interface.
Scrollable interface Dimension getPreferredScrollableViewportSize() int getScrollableBlockIncrement() int getScrollableUnitIncrement() boolean getScrollableTracksViewportWidth() boolean getScrollableTracksViewportHeight()
Copyright 2003 Mudra Services
18
SWING - JScrollPane
class ScrollableImage extends JLabel implements Scrollable { public ScrollableImage(Icon icon) { super(icon); }
public Dimension getPreferredScrollableViewportSize() { return(new Dimension(300,300)); }
public int getScrollableBlockIncrement(Rectangle visibleRect ,int orientation,int direction) { return(20); }
Copyright 2003 Mudra Services
19
SWING - JScrollPane
public int getScrollableUnitIncrement(Rectangle visibleRect ,int orientation,int direction) { return(20); }
public boolean getScrollableTracksViewportWidth() { return(false); }
public boolean getScrollableTracksViewportHeight() { return(false); } }
Copyright 2003 Mudra Services
20
SWING - JSplitPane
View two or more pieces of information simultaneously
Resize any panel to view more or less data Orientation
left-to-right top-to-bottom
Text editors usually have split windows to create multiple copies of the same text file. This allows you to look at different parts of the
text document at the same time.
Copyright 2003 Mudra Services
21
SWING - JSplitPane
A window split into two panels
Vertical Split
Copyright 2003 Mudra Services
22
SWING - JSplitPane
package splitexample;import java.awt.*;import javax.swing.*;public class SplitExample extends JFrame { public SplitExample() {
// create panel 2 private JPanel createPanel2() { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS)); panel.setBorder(BorderFactory.createEtchedBorder()); panel.add(new JCheckBox("Check if you are still in school")); panel.add(new JCheckBox("Check if you have no medical
problems")); return(panel); }
} // end
Copyright 2003 Mudra Services
26
SWING - JSplitPane
One split pane can be nested into another split pane for a more complex interface
Setting the divider size splitpane.setDividerSize(20)
A divider movement can be detected by using the AncestorListener Components of the split pane can implement
it
Copyright 2003 Mudra Services
27
SWING - JEditorPane
Extends from the JTextComponent class Ability to display any mime type Can easily create an HTML viewer for
public EditorPaneExample() { try { setSize(600,600);
Copyright 2003 Mudra Services
29
SWING - JEditorPane
// create an editor pane pointing to a URL URL url = new URL("file:///D:/OLDui/index.html"); editorpane = new JEditorPane(url); editorpane.setEditable(false); editorpane.addHyperlinkListener(this);
// wrap the editor pane in a scroll pane JScrollPane scrollpane = new JScrollPane(); scrollpane.getViewport().add(editorpane,BorderLayout.CENTER);
// add the pane to the frame getContentPane().add(scrollpane,BorderLayout.CENTER); } catch (Exception exp) { System.out.println(exp.getMessage()); } }
Copyright 2003 Mudra Services
30
SWING - JEditorPane
public void hyperlinkUpdate(HyperlinkEvent event) { if (event.getEventType() ==
HyperlinkEvent.EventType.ACTIVATED) { // User clicked on a URL try { editorpane.setPage(event.getURL()); } catch (Exception exp) { System.out.println("Error :: " + exp.getMessage()); } } }
Copyright 2003 Mudra Services
31
SWING - JEditorPane
public static void main(String[] args) { EditorPaneExample editorPaneExample = new
Swing handles RTF other than HTML Custom formats can be handled by
setting up custom editor kits
Copyright 2003 Mudra Services
32
SWING - Action
Synchronizing the action listeners for toolbars buttons, menu items and popup menu items is a nightmare
Synchronizing enabling/disabling is a problem
Actions are the solution to avoid synchronization and foster code reuse
An action object can be added to a toolbar, menu or a popup menu
Action object can be disabled/enabled
Copyright 2003 Mudra Services
33
SWING - Action
Action class should extend from AbstractAction
public class XAction extends AbstractAction {public XAction(String name,ImageIcon image) {
super(name,image);}
public void actionPerformed(ActionEvent event) {// Handle action event for X here
}}
Copyright 2003 Mudra Services
34
SWING - Action
Shows the disabled actions
Copyright 2003 Mudra Services
35
SWING - Action
package actionexample;import java.awt.*;import javax.swing.*;import java.awt.event.*;public class ActionExample extends JFrame { private JPopupMenu popup = new JPopupMenu();
// Handle right clicks public class MouseHandler extends MouseAdapter { public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(),e.getX(),e.getY()); } } }
Copyright 2003 Mudra Services
36
SWING - Action
// Action class for 'New' class NewAction extends AbstractAction { NewAction(String name,ImageIcon icon) { super(name,icon);
}
public void actionPerformed(ActionEvent e) { // handle new action } }
Copyright 2003 Mudra Services
37
SWING - Action
// Action class for 'Save' class SaveAction extends AbstractAction { SaveAction(String name,ImageIcon icon) { super(name,icon);
}
public void actionPerformed(ActionEvent e) { // handle save action } }
Copyright 2003 Mudra Services
38
SWING - Action
// Action class for 'SaveAll' class SaveAllAction extends AbstractAction { SaveAllAction(String name,ImageIcon icon) { super(name,icon);
ActionExample actionExample = new ActionExample();
// pack and show actionExample.setVisible(true); }
}
Copyright 2003 Mudra Services
43
SWING - JDialog
Secondary application window Almost like a JFrame
But supports modal operation. Extends from the Dialog class in AWT
Copyright 2003 Mudra Services
44
SWING - JDialog
A JDialog window
Copyright 2003 Mudra Services
45
SWING - JDialog
package dialogexample;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class DialogExample extends JFrame implements ActionListener { public DialogExample() { // exit the frame on close this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create a JButton and add it to the content pane JButton jbutton = new JButton("Open Dialog"); jbutton.addActionListener(this); getContentPane().add(jbutton); }
Copyright 2003 Mudra Services
46
SWING - JDialog
public void actionPerformed(ActionEvent e) { // when the button is clicked, control comes here TestDialog dialog = new TestDialog(this,"Test Dialog",true);
dialog.pack(); dialog.setVisible(true); }
public static void main(String[] args) { DialogExample dialogExample = new DialogExample();
public class TestInternalFrame extends JInternalFrame { public TestInternalFrame() { super("Internal Frame");
// set the frame properties setClosable(true); setMaximizable(true); setIconifiable(true); setResizable(true);
Copyright 2003 Mudra Services
63
SWING - JInternalFrame
// set the size and add test area setSize(400,400); getContentPane().add("Center",new JTextArea()); }
} // end TestInternalFrame
Other methods moveToFront() moveToBack() setMenuBar(JMenuBar menubar) addInternalFrameListener(InternalFrameListener listener)
Copyright 2003 Mudra Services
64
SWING – Exercise 3
Copyright 2003 Mudra Services
65
SWING – Exercise
Create a UI layout as shown in the previous page. When the frame is first shown the label at the bottom should say “File not selected”. When the user clicks on button and chooses a file or directory, the label text should change to the full absolute path of the file.
When the window is closed, the application should exit.
Copyright 2003 Mudra Services
66
SWING - JList
Collection of items from which user can make one or more selection
Has the ability to provide graphics inside the list
Copyright 2003 Mudra Services
67
SWING - JList
Jlist accepts String[], Vector or ListModel
String[] items = new String[] {
"item1","item2","item3","item4" ,"item5","item6","item7","item8" ,"item9","item10" }; JList list = new JList(items); list.setVisibleRowCount(5); getContentPane().add("Center",new JScrollPane(list));
// Custom model class TestModel extends AbstractListModel { public int getSize() { return(items.length); }
public Object getElementAt(int index) { return(items[index]); } } // end TestModel
Copyright 2003 Mudra Services
72
SWING - JList
// Custom cell renderer class CustomCellRenderer extends JLabel implements ListCellRenderer { public CustomCellRenderer() { setOpaque(true); }
public Component getListCellRendererComponent(JList list ,Object value ,int index,boolean isSelected,boolean cellHasFocus) { this.setText(value.toString()); this.setIcon(new ImageIcon(images[index])); if (isSelected) { this.setBackground(Color.blue); this.setForeground(Color.white); }
public ListExample() { setSize(200,200); JList list = new JList(new TestModel()); list.setCellRenderer(new CustomCellRenderer()); getContentPane().add("Center",new JScrollPane(list)); }
Copyright 2003 Mudra Services
74
SWING - JList
public static void main(String[] args) { ListExample listExample = new ListExample(); listExample.setVisible(true); }}
Copyright 2003 Mudra Services
75
SWING - JList
Listening to list activity addListSelectionListener ListSelectionEvent
Any component can be rendered inside the list box. JButton JTextField JCheckBox etc
Copyright 2003 Mudra Services
76
SWING - JTable
Simple two dimensional display Supports custom data models Supports custom cell rendering
Render any component inside the cell Support custom header rendering Highly flexible component
Can be customized by the programmer Class is called JTable
Copyright 2003 Mudra Services
77
SWING - JTable
A JTable which shows information about people
Copyright 2003 Mudra Services
78
SWING - JTable
package simpletable;import java.awt.*;import javax.swing.*;public class SimpleTableExample extends JFrame { public SimpleTableExample() { setSize(600,300);
// create the columns and the values String[] columns = {"Name","Telephone","City","Company"}; String values[][] = { {"Mr. X","703-4228989","Herndon","Bell Atlantic"}, {"Mr. Z","301-6748989","Rockville","Artesia Tech"}, {"Mr. W","703-4258999","Herndon","Intersect Soft"}, {"Mr. A","703-7864456","Herndon","Intelsat"} };
Copyright 2003 Mudra Services
79
SWING - JTable
JTable table = new JTable(values,columns); JScrollPane pane = new JScrollPane(table);
// add the table to the frame getContentPane().add(pane); }
public static void main(String[] args) { SimpleTableExample simpleTableExample = new SimpleTableExample(); simpleTableExample.setVisible(true); }
} // end program
Copyright 2003 Mudra Services
80
SWING - JTable
JTable uses the DefaultDataModel class as the model by default
A custom data model can be created for the table by extending AbstractTableModel
Copyright 2003 Mudra Services
81
SWING - JTable
Using a custom table model
Copyright 2003 Mudra Services
82
SWING - JTable
package simpletable;import java.awt.*;import javax.swing.*;import javax.swing.table.*;public class SimpleTableExample extends JFrame { public SimpleTableExample() { // set the size of the frame setSize(600,300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(new SimpleTableModel()); table.setShowHorizontalLines(false); JScrollPane pane = new JScrollPane(table); pane.getViewport().setBackground(Color.white);
Set the tableBackground to white
Copyright 2003 Mudra Services
83
SWING - JTable
// add the table to the frame
getContentPane().add(pane); }
public static void main(String[] args) { SimpleTableExample simpleTableExample
= new SimpleTableExample(); simpleTableExample.setVisible(true); }
public void valueChanged(ListSelectionEvent event) {
if (event.getSource() == table.getSelectionModel() && !event.getValueIsAdjusting()) { int row = table.getSelectedRow(); if (row >= 0) { SimpleTableModel model = (SimpleTableModel)table.getModel(); String name = (String)model.getValueAt(row,0);
= new DefaultMutableTreeNode(types[index]); return(node); }
Copyright 2003 Mudra Services
106
SWING - JTree
else if (userObject.equals("Imports")) { String[] imports = file.getImports(); DefaultMutableTreeNode node
= new DefaultMutableTreeNode(imports[index]); return(node); } else if (userObject.equals("Data")) { String[] variables = file.getVariables(); DefaultMutableTreeNode node
= new DefaultMutableTreeNode(variables[index]); return(node); }
Copyright 2003 Mudra Services
107
SWING - JTree
else if (userObject.equals("Methods")) { String[] methods = file.getMethods(); DefaultMutableTreeNode node
= new DefaultMutableTreeNode(methods[index]);
return(node); }
return(null);
} // end getChild()
Copyright 2003 Mudra Services
108
SWING - JTree
// get the child count for the parent public int getChildCount(Object parent) { DefaultMutableTreeNode parentNode
= (DefaultMutableTreeNode)parent; String userObject = (String)parentNode.getUserObject(); if (userObject.equals(rootName)) { return(file.getSubTypes().length); } else if (userObject.equals("Imports")) { return(file.getImports().length); }
Copyright 2003 Mudra Services
109
SWING - JTree
else if (userObject.equals("Data")) { return(file.getVariables().length); } else if (userObject.equals("Methods")) { return(file.getMethods().length); }
return(0);
} // end getChildCount()
Copyright 2003 Mudra Services
110
SWING - JTree
// return TRUE if the node is a leaf public boolean isLeaf(Object node) { DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)node; String userObject = (String)parentNode.getUserObject(); if (userObject.equals(rootName) || userObject.equals("Imports") || userObject.equals("Data") || userObject.equals("Methods")) { return(false); } return(true); }
} // end SimpleTreeModel
Copyright 2003 Mudra Services
111
SWING - JTree
Custom Rendering Useful for changing icons, fonts etc Implement TreeCellRenderer class Component
getTreeCellRendererComponent(…) must be implemented
Nodes can contain any Component (TextField, Checkbox etc)
Listening to tree selections Implement TreeSelectionListener
Copyright 2003 Mudra Services
112
SWING - JTree
Listening for Tree expansions Implement TreeExpansionListener
Hiding root node tree.setRootVisible(false);
Other methods tree.expandPath(path) tree.collapsePath(path) tree.setSelectionPath(path) tree.clearSelection()
Copyright 2003 Mudra Services
113
SWING – Exercise 4
Copyright 2003 Mudra Services
114
SWING – Exercise 4
Add a JTable to the center panel which shows the name of the file/directory and the size as columns. Whenever a file or directory is chosen it should update the table.
What mechanism would you use to make the size column right justified?
Copyright 2003 Mudra Services
115
SWING – Look And Feel
Supports different look and feel Metal Motif Windows Mac
MVC pattern Can create corporate look and feel Change the look And Feel