Swing Programming
Swing Programming
Overview
Swings Architecture & background Basic Swing Programming Swing lists Swing tables Swing trees Swing trees
What's Swing?
Swing is Suns alternate Windowing Framework Part of the JFC (Java Foundation Classes)
Standard part of Java 2
Using Swing
Swing should not be combined with AWT
Each Window should be fully Swing or fully AWT
Since Swing matches the AWTs Swing matches the AWTs functionality, thats not hard functionality, thats not hard
Most Swing components are upwards-compatible with their AWT counterparts easy to change code from AWT to Swing
Swing Architecture
Swing follows the MVC paradigm paradigm for building user building user interfaces
Each UI Component has a has a model
gestures and events View change notification Model Controller
data access
data change
Top-level hierarchy
Each top-level top-level class adds new behavior to to existing AWT components
Applet Frame
Window
Dialog
JApplet
JFrame
JDialog
JFrames
A JFrame acts like an AWT Frame
Except it handles Swing component handles component nesting
JComponent
AbstractButton
JComboBox
JLabel
JList
JPanel
JSlider
JTable
JTree
JTabbedPane
JScrollPane
JButton
JMenuItem
JToggleButton
Borders
Any JComponent can have a Border placed on it
Usually only used on JPanels on JPanels
JTitledBorder Example
public ExampleWithGroupBox ( ) { super(); JPanel aPanel = new JPanel(); aPanel.setLayout(new BorderLayout()); TitledBorder border = BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(2), "Group"); aPanel.setBorder(border); getContentPane().add(aPanel); JLabel hello = new JLabel("Hello World"); aPanel.add(hello, BorderLayout.CENTER); }
JTabbedPane
A JTabbedPane represents a notebook JTabbedPane represents a notebook
Any JComponent can be a page in a JTabbedPane JPanels are usually used
Tabs can be added, inserted at runtime, added, inserted at runtime, deleted and selected
public JPanel buildTabOne() { JPanel aPanel = new JPanel(); JLabel first = new JLabel("This is the first tab"); aPanel.add(first, BorderLayout.CENTER); return aPanel; }
JTabbedPane Details
Tabs are indexed from 0
JTabbedPane.getTabCount();
JTabbedPane Events
The JTabbedPane supports the ChangedEvent notification Clients must implement the ChangeListener interface ChangeListener interface
void stateChanged(ChangeEvent e) stateChanged(ChangeEvent
JScrollPane
A JScrollPane manages scrolling over a larger view larger view
It manages a viewport on the view It manages a viewport on the view
Viewport
View
JScrollPane example
/* * Add a Scroll pane to the Jframe. Put a JLabel having * the numbers 0 - 49 into the scrollPanes viewport * */ public ExampleScrolling ( ) { super(); JScrollPane scroller = new JScrollPane(); getContentPane().add(scroller); StringBuffer bigBuffer = new StringBuffer(); for (int i=0; i<50; i++) { bigBuffer.append(Integer.toString(i)); bigBuffer.append(' ');
}
Scrollable Interface
Components that will be scrolled by a JScrollPane should implement the JScrollPane should implement the Interface Scrollable
Most Swing components implement this components already
JSplitPane
A JSplitPane is a splitter pane that allows the user to resize two components the user to resize two components dynamically
Can split horizontally or vertically split horizontally or vertically
JSplitPane Example
public ExampleWithSplitPane ( ) { JSplitPane splitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitter.setLeftComponent(new JTextArea()); splitter.setRightComponent(new JTextArea()); getContentPane().add(splitter); }
public static void main(String args[]) { ExampleWithSplitPane example = new ExampleWithSplitPane(); example.pack(); example.setVisible(true); }
JProgressBar
A JProgressBar is a standard JProgressBar is a standard Windows-like progress indicator
LED-like display like a Stereo system LED-like display like a Stereo system
It is usually used in its own Frame or usually used in its own Frame or dialog
Often combined with one or more labels more labels
JSlider
A JSlider is a volume-control slider JSlider is a volume-control slider component
Familiar in many Windows applications
JSlider Example
public ExampleWithSlider ( ) { JPanel aPanel = new JPanel(); aPanel.setLayout(new BorderLayout()); getContentPane().add(aPanel); public void stateChanged(ChangeEvent e) { int value = ((JSlider) e.getSource()).getValue(); counterLabel.setText(Integer.toString(value)); }
counterLabel = new JLabel("0"); aPanel.add(counterLabel, BorderLayout.SOUTH); JSlider slider = new JSlider(SwingConstants.HORIZONTAL, 0, 100, 0); slider.setMajorTickSpacing(20); slider.setMinorTickSpacing(10); slider.setPaintTicks(true); slider.setPaintLabels(true); slider.addChangeListener(this); aPanel.add(slider, BorderLayout.NORTH); }
AbstractButton Hierarchy
Swing has a number of has a number of button components
push buttons, radio buttons, radio buttons, check boxes
AbstractButton ActionListener <<interface>> actionPerformed( )
Usually each will use an each will use an ActionListener to hook into UI actions
JButton
JToggleButton
JCheckBox
JRadioButton
JButton Example
public ExampleJButton() { super(); JPanel aPanel = new JPanel(); aPanel.setLayout(new BorderLayout()); getContentPane().add(aPanel); public void buttonPushed() { System.out.println("The button was pushed"); }
JButton push = new JButton("Push Me"); push.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { buttonPushed(); } }); aPanel.add(push, BorderLayout.NORTH); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); }
JMenu Hierarchy
Swing Menus are similar Menus are similar to Buttons
JMenuItems also have ActionListeners This is because they are AbstractButtons
JComponent
JMenuBar
AbstractButton
JPopupMenu
JMenuItem
JMenu
JCheckBoxMenuItem
JRadioButtonMenuItem
JMenu Example
JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); // method of JFrame JMenu testMenu = new JMenu("Test"); JMenuItem menuItem = new JMenuItem("Select Me"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { menuSelected(); } }); testMenu.add(menuItem); menuBar.add(testMenu);
Text Handling
Swing has text handling capabilities similar to capabilities similar to AWT
JTextField, JPasswordField, JTextArea
DocumentListener <<interface>>
JTextComponent
Document <<interface>>
However, it also has sophisticated support for viewing HTML and RTF viewing HTML and RTF
JEditorPane
JTextField
JTextArea
JEditorPane
JList
JList is the primary Swing list class Its like the AWT List widget except:
The widget doesnt support adding & removing elements directly removing elements directly Adds customized data models customized models Adds custom element rendering
JList Constructors
Jlist has four constructors Jlist has four constructors
JList() JList(Object[]) JList(Vector) JList(ListModel)
Use the array and Vector versions only for simple, static lists simple, static lists
For more complex lists, use a ListModel
ListModel
A ListModel ListModel represents a list of represents a list of elements to a JList elements to a JList Subclass Subclass AbstractListModel AbstractListModel to override getSize() override getSize() and getElementAt() getElementAt()
ListModel <<interface>> getSize( ) getElementAt( ) addListDataListener( ) removeListDataListener( ) ListDataListener <<interface>> contentsChanged( ) intervalAdded( ) intervalRemoved( )
ListModels
There would be several reasons you might make a ListModel might make a ListModel
Loading database information as it is requested Synthetic lists of calculated items
As our example well store information our example well store information in a hashtable, and display the keys as they were added to the hashtable
Example ListModel
public class CustomListModel extends AbstractListModel { Hashtable data = new Hashtable(); Vector orderedKeys = new Vector(); public void put(Object key, Object value) { data.put(key, value); if (!orderedKeys.contains(key)) orderedKeys.addElement(key); fireContentsChanged(this, -1, -1); } public Object get(Object key) { return data.get(key);} public Object getElementAt(int index) { return orderedKeys.elementAt(index);} public int getSize() { return orderedKeys.size();} }
ListModel Example
public ExampleCustomListModelList ( ) { JPanel outerPanel = new JPanel(); outerPanel.setLayout(new BorderLayout()); JScrollPane scroller = new JScrollPane(); public void actionPerformed(ActionEvent e) { model.put("As", "If"); }
JList aList = new JList(buildCustomListModel()); scroller.getViewport().add(aList); JButton button = new JButton("Add"); button.addActionListener(this); outerPanel.add(scroller, BorderLayout.NORTH); outerPanel.add(button, BorderLayout.SOUTH); getContentPane().add(outerPanel); }
JList Events
JLists support the ListSelection event support the ListSelection event notification Clients implement the ListSelectionListener interface
void valueChanged(ListSelectionEvent e) void valueChanged(ListSelectionEvent e)
JTable
JTable is a Tabular (row-column) view with read-only or editable cells Can create a JTable on:
Two Arrays 2d array of data, 1d array of column headings Two Vectors (data of length row X columns), column columns), headings TableModel, (optionally) ListSelectionModel and TableColumnModel
Table Models
TableModel is an interface that defines the row/column behavior
AbstractTableModel implements most of the behavior you implement getColumnCount(), getRowCount(), getValueAt() getValueAt()
TableModel <<interface>> getColumnCount( ) getRowCount( ) getValueAt( ) isCellEditable( )
AbstractTableModel
JDBCAdapter
YourTableModel
Table Selection
There are several selection attributes of several selection attributes of JTable you can set
setRowSelectionAllowed(boolean value) setColumnSelectionAllowed(boolean value) setSelectionForeground(Color value) value) setSelectionBackground(Color value)
You can also turn horizontal and vertical lines on and off
List Selection
JTables support ListSelection notification
Clients must implement the ListSelectionListener interface Just like JLists in that respect Just
The Event doesnt carry the necessary Event doesnt carry the necessary selection information selection information
You need to query the table for selection information Use getSelectedRow(), getSelectedRow(), getSelectedColumn(), getValueAt()
TableSelectionListener Example
public class ExampleTableSelection extends JFrame implements ListSelectionListener { ExampleTableSelection() { JTable table = new JTable(someModel); ListSelectionModel selectionModel = table.getSelectionModel(); selectionModel.addListSelectionListener(this); } public void valueChanged(ListSelectionEvent e) { JTable table = (JTable) e.getSource(); DefaultTableModel model = (DefaultTableModel) table.getModel(); int row = table.getSelectedRow(); int column = table.getSelectedColumn(); String value = (String) model.getValueAt(row, column); System.out.println(Selected value is + value); } }
Swing Trees
JTree is a hierarchical display component
allows expansion, contraction, editing of allows expansion, contraction, editing of nodes
TreeModel Hierarchy
TreeNode is an interface TreeNode is an interface that describes node describes node behavior MutableTreeNode is an interface that allows addition/removal of addition/removal of children DefaultMutableTreeNode implements MutableTreeNode MutableTreeNode
TreeNode Example
public DefaultMutableTreeNode buildTree() { DefaultMutableTreeNode root = new DefaultMutableTreeNode("Classes"); DefaultMutableTreeNode level1a = new DefaultMutableTreeNode("Java"); DefaultMutableTreeNode level1b = new DefaultMutableTreeNode("Smalltalk"); root.add(level1a); root.add(level1b); level1a.add(new DefaultMutableTreeNode("Introduction to Java")); level1a.add(new DefaultMutableTreeNode("Advanced Java")); level1a.add(new DefaultMutableTreeNode("Enterprise Java Programming")); return root; }
public ExampleSimpleTree() { JScrollPane scroller = new JScrollPane(); JTree tree = new JTree(buildTree()); scroller.getViewport().add(tree); getContentPane().add(scroller); }
Tree Selection
JTrees support the TreeSelectionEvent support the TreeSelectionEvent notification
Clients must implement the TreeSelectionListener interface void valueChanged(TreeSelectionEvent e)
Use the JTree method getSelectionPath() to get a TreePath that gives the selection(s)
Tree Expansion
JTrees also support the also support the TreeExpansionEvent notification
Clients implement TreeExpansionListener implement TreeExpansionListener void treeExpanded(TreeExpansionEvent e) void treeCollapsed(TreeExpansionEvent e) treeCollapsed(TreeExpansionEvent
You can ask the TreeExpansionEvent to can ask the TreeExpansionEvent to getPath() and return the affected path getPath() and return the affected path
Summary
Swing is a comprehensive expansion and is a comprehensive expansion and replacement for AWT You've seen some basic and advanced seen some basic and advanced concepts in Swing Programming
More Information
For more information, see the Swing tutorials on the Sun Java Developer's the Sun Java Developer's Connection website (http://developer.java.sun.com)
requires registration (free) requires registration (free)
Steven Gutz, "Up to Speed With Swing, 2nd Edition", Manning, 2000