Java Swing ProgrammingProgramming Kyle Brown · Java Swing Java Swing ProgrammingProgramming Kyle...
-
Upload
hoangduong -
Category
Documents
-
view
303 -
download
6
Transcript of Java Swing ProgrammingProgramming Kyle Brown · Java Swing Java Swing ProgrammingProgramming Kyle...
Java Swing Java Swing ProgrammingProgrammingKyle BrownKyle BrownIBM WebSphere ServicesIBM WebSphere Services
OverviewOverviewSwing’s Architecture & backgroundSwing’s Architecture & backgroundBasic Swing ProgrammingBasic Swing ProgrammingSwing listsSwing listsSwing tablesSwing tablesSwing treesSwing trees
What's Swing?What's Swing?Swing is Sun’s alternate Windowing Swing is Sun’s alternate Windowing FrameworkFrameworkPart of the JFC (Java Foundation Part of the JFC (Java Foundation Classes)Classes)
Standard part of Java 2Standard part of Java 2A full replacement/alternative to AWTA full replacement/alternative to AWTFound in packages starting with Found in packages starting with javax.swingjavax.swing
Key Features of SwingKey Features of SwingNot based on windowing systemNot based on windowing system
all Swing components are lightweightall Swing components are lightweightPluggable Look and Feel (PLAF)Pluggable Look and Feel (PLAF)
Richer component set than AWTRicher component set than AWTDoesn’t take the “least common Doesn’t take the “least common denominator” approachdenominator” approachincludes components not found in *any* includes components not found in *any* windowing systemwindowing systemadds functionality to components that adds functionality to components that already have counterparts in the AWTalready have counterparts in the AWT
Using SwingUsing SwingSwing should not be combined with Swing should not be combined with AWTAWT
Each Window should be fully Swing or Each Window should be fully Swing or fully AWTfully AWT
Since Swing matches the AWT’s Since Swing matches the AWT’s functionality, that’s not hardfunctionality, that’s not hard
Most Swing components are Most Swing components are upwards-compatible with their AWT upwards-compatible with their AWT counterpartscounterpartseasy to change code from AWT to Swingeasy to change code from AWT to Swing
Swing ArchitectureSwing ArchitectureSwing follows the Swing follows the MVC paradigm MVC paradigm for building user for building user interfacesinterfaces
Each UI Each UI Component has a Component has a modelmodel
We will often We will often customize certain customize certain Swing modelsSwing models
data changechangenotification data access
gestures andevents
View Controller
Model
Basic Swing ProgrammingBasic Swing ProgrammingAs noted previously, Swing adds an As noted previously, Swing adds an entirely new set of components to Javaentirely new set of components to Java
Upward-compatible with their AWT Upward-compatible with their AWT counterpartscounterpartsWe won’t deeply cover those similar to We won’t deeply cover those similar to their AWT counterpartstheir AWT counterparts
We will start at the bottomWe will start at the bottomJFrameJFrameJappletJapplet
Top-level hierarchyTop-level hierarchyEach top-level Each top-level class adds new class adds new behavior to behavior to existing AWT existing AWT componentscomponents
Frame
JFrame
Dialog
JDialog
Applet
JApplet
Window
Comparing Swing & AWTComparing Swing & AWT
import java.awt.*;
public class ExampleAWTFrame extends java.awt.Frame {
public ExampleAWTFrame ( ) {super();Panel aPanel = new Panel();aPanel.setLayout(new BorderLayout());add(aPanel);Label hello = new Label("Hello World");aPanel.add(hello, BorderLayout.NORTH);
}
public static void main(String args[]) {ExampleAWTFrame aFrame = new ExampleAWTFrame();aFrame.setVisible(true);
}}
Comparing Swing & AWTComparing Swing & AWTimport java.awt.*;import com.sun.java.swing.*;
public class ExampleSwingJFrame extends com.sun.java.swing.JFrame {
public ExampleSwingJFrame() {super();JPanel aPanel = new JPanel();aPanel.setLayout(new BorderLayout());getContentPane().add(aPanel);JLabel hello = new JLabel("Hello World");aPanel.add(hello, BorderLayout.NORTH);
}
public static void main(String args[]) {ExampleSwingJFrame aFrame = new ExampleSwingJFrame();aFrame.setVisible(true);
}}
JFramesJFramesA JFrame acts like an AWT FrameA JFrame acts like an AWT Frame
Except it handles Swing component Except it handles Swing component nestingnesting
A JFrame is really two “panes”A JFrame is really two “panes”A “LayeredPane” that has an optional A “LayeredPane” that has an optional menu bar and a content panemenu bar and a content paneA “GlassPane” that sits transparently in A “GlassPane” that sits transparently in front of the LayeredPanefront of the LayeredPane
Partial Swing HierarchyPartial Swing Hierarchy
JComponent
AbstractButton
JButton JToggleButtonJMenuItem
JComboBox JPanelJLabel JList JSlider JTreeJTable
JTabbedPane JScrollPane
Container
BordersBordersAny JComponent can have a Border Any JComponent can have a Border placed on itplaced on it
Usually only used on JPanelsUsually only used on JPanelsSpecify the border withSpecify the border with
aJComponent.setBorder(Border aBorder)aJComponent.setBorder(Border aBorder)
Common Borders include BevelBorder, Common Borders include BevelBorder, TitledBorderTitledBorder
Normally built with a BorderFactoryNormally built with a BorderFactory
JTitledBorder ExampleJTitledBorder 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);}
JTabbedPaneJTabbedPaneA JTabbedPane represents a “notebook”A JTabbedPane represents a “notebook”
Any JComponent can be a page in a Any JComponent can be a page in a JTabbedPaneJTabbedPaneJPanels are usually usedJPanels are usually used
Tabs can be added, inserted at runtime, Tabs can be added, inserted at runtime, deleted and selecteddeleted and selected
Creating TabsCreating Tabs
public ExampleWithTabbedPane ( ) {super();JTabbedPane tabs = new JTabbedPane();tabs.addTab("Page1", buildTabOne());tabs.addTab("Page2", buildTabTwo());tabs.addTab("Page3", buildTabThree());getContentPane().add(tabs);
}
public JPanel buildTabOne() {JPanel aPanel = new JPanel();JLabel first = new JLabel("This is the first tab");aPanel.add(first, BorderLayout.CENTER);return aPanel;
}
JTabbedPane DetailsJTabbedPane DetailsTabs are indexed from 0Tabs are indexed from 0
JTabbedPane.getTabCount();JTabbedPane.getTabCount();Can remove tabs withCan remove tabs with
JTabbedPane.removeTabAt(index);JTabbedPane.removeTabAt(index);Can select a tab withCan select a tab with
JTabbedPane.setSelectedIndex(index)JTabbedPane.setSelectedIndex(index)
JTabbedPane EventsJTabbedPane EventsThe JTabbedPane supports the The JTabbedPane supports the ChangedEvent notificationChangedEvent notificationClients must implement the Clients must implement the ChangeListener interfaceChangeListener interface
void stateChanged(ChangeEvent e)void stateChanged(ChangeEvent e)No state information is passed inNo state information is passed in
query the source for the new statequery the source for the new state
JScrollPaneJScrollPaneA JScrollPane manages scrolling over a A JScrollPane manages scrolling over a larger viewlarger view
It manages a viewport on the viewIt manages a viewport on the view
Viewport
View
JScrollPane exampleJScrollPane example
/** Add a Scroll pane to the Jframe. Put a JLabel having* the numbers 0 - 49 into the scrollPane’s 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(' '); }
JLabel longLabel = new JLabel(bigBuffer.toString()); scroller.getViewport().add(longLabel);}
Scrollable InterfaceScrollable InterfaceComponents that will be scrolled by a Components that will be scrolled by a JScrollPane should implement the JScrollPane should implement the Interface ScrollableInterface Scrollable
Most Swing components implement this Most Swing components implement this alreadyalready
This Interface defines methods toThis Interface defines methods toreturn the preferred size of the viewportreturn the preferred size of the viewportget the increment in pixels to scroll by unit get the increment in pixels to scroll by unit and blockand block
JSplitPaneJSplitPaneA JSplitPane is a “splitter” pane that A JSplitPane is a “splitter” pane that allows the user to resize two components allows the user to resize two components dynamicallydynamically
Can split horizontally or verticallyCan split horizontally or verticallyUse the constant Use the constant JSplitPane.VERTICAL_SPLIT or JSplitPane.VERTICAL_SPLIT or JSplitPane.HORIZONTAL_SPLIT in JSplitPane.HORIZONTAL_SPLIT in the constructorthe constructor
JSplitPane ExampleJSplitPane 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);}
JProgressBarJProgressBarA JProgressBar is a standard A JProgressBar is a standard Windows-like progress indicatorWindows-like progress indicator
LED-like display like a Stereo systemLED-like display like a Stereo systemIt is usually used in its own Frame or It is usually used in its own Frame or dialogdialog
Often combined with one or more labelsOften combined with one or more labels
JSliderJSliderA JSlider is a volume-control slider A JSlider is a volume-control slider componentcomponent
Familiar in many Windows applicationsFamiliar in many Windows applicationsJsliders have a variety of attributesJsliders have a variety of attributes
Major and Minor TicksMajor and Minor TicksLabelsLabelsMinimum & Maximum valuesMinimum & Maximum values
Clients watch for the ChangeEvent Clients watch for the ChangeEvent notificationnotification
Similar to JTabbedPaneSimilar to JTabbedPane
JSlider ExampleJSlider Examplepublic ExampleWithSlider ( ) { JPanel aPanel = new JPanel(); aPanel.setLayout(new BorderLayout()); getContentPane().add(aPanel);
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);}
public void stateChanged(ChangeEvent e) { int value = ((JSlider) e.getSource()).getValue(); counterLabel.setText(Integer.toString(value));}
AbstractButton HierarchyAbstractButton HierarchySwing has a number of Swing has a number of button componentsbutton components
push buttons, radio push buttons, radio buttons, check boxesbuttons, check boxes
Usually each will use an Usually each will use an ActionListener to hook ActionListener to hook into UI actionsinto UI actions
actionPerformed( )
AbstractButton ActionListener<<interface>>
JButton JToggleButton
JCheckBox JRadioButton
JButton ExampleJButton Examplepublic ExampleJButton() {
super();JPanel aPanel = new JPanel();aPanel.setLayout(new BorderLayout());getContentPane().add(aPanel);
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);}
});}
public void buttonPushed() {System.out.println("The button was pushed");
}
JMenu HierarchyJMenu HierarchySwing Menus are similar Swing Menus are similar to Buttonsto Buttons
JMenuItems also have JMenuItems also have ActionListenersActionListenersThis is because they are This is because they are AbstractButtonsAbstractButtons
JComponent
JMenuBar AbstractButton
JCheckBoxMenuItem JRadioButtonMenuItem
JMenuItem
JMenu
JPopupMenu
JMenu ExampleJMenu Example
JMenuBar menuBar = new JMenuBar();setJMenuBar(menuBar); // method of JFrameJMenu 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 HandlingText HandlingSwing has text handling Swing has text handling capabilities similar to capabilities similar to AWTAWT
JTextField, JTextField, JPasswordField, JPasswordField, JTextAreaJTextArea
However, it also has However, it also has sophisticated support for sophisticated support for viewing HTML and RTFviewing HTML and RTF
JEditorPaneJEditorPane
JTextComponent Document<<interface>>
JTextField JTextArea JEditorPane
DocumentListener<<interface>>
JListJListJList is the primary Swing list classJList is the primary Swing list classIt’s like the AWT List widget except:It’s like the AWT List widget except:
The widget doesn’t support adding & The widget doesn’t support adding & removing elements directlyremoving elements directlyAdds customized data modelsAdds customized data modelsAdds custom element renderingAdds custom element rendering
Simple JList ExampleSimple JList Example
/** You must place a Jlist inside a JScrollPane to get scroll bars!*/
public ExampleSimpleList ( ) { String[] strings = {"Bob", "Carol", "Ted", "Alice", "Jane", "Fred", "Sue"}; JScrollPane scroller = new JScrollPane(); JList aList = new JList(strings); scroller.getViewport().add(aList); getContentPane().add(scroller);}
JList ConstructorsJList ConstructorsJlist has four constructorsJlist has four constructors
JList()JList()JList(Object[])JList(Object[])JList(Vector)JList(Vector)JList(ListModel)JList(ListModel)
Use the array and Vector versions only Use the array and Vector versions only for simple, static listsfor simple, static lists
For more complex lists, use a ListModelFor more complex lists, use a ListModel
ListModelListModel
A ListModel A ListModel represents a list of represents a list of elements to a JListelements to a JListSubclass Subclass AbstractListModel AbstractListModel to override getSize() to override getSize() and getElementAt()and getElementAt()
contentsChanged( )
ListModel
getSize( )getElementAt( )addListDataListener( )removeListDataListener( )
AbstractListModel
addListDataListener( )removeListDataListener( )
ListDataListener
intervalAdded( )intervalRemoved( )
<<interface>> <<interface>>
fireContentsChanged( )
fireIntervalAdded( )
fireIntervalRemoved( )
ListModelsListModelsThere would be several reasons you There would be several reasons you might make a ListModelmight make a ListModel
Loading database information as it is Loading database information as it is requestedrequested“Synthetic” lists of calculated items“Synthetic” lists of calculated items
As our example we’ll store information As our example we’ll store information in a hashtable, and display the keys as in a hashtable, and display the keys as they were added to the hashtablethey were added to the hashtable
Example ListModelExample ListModelpublic 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 ExampleListModel Examplepublic ExampleCustomListModelList ( ) {
JPanel outerPanel = new JPanel();outerPanel.setLayout(new BorderLayout());JScrollPane scroller = new JScrollPane();
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);
}
public void actionPerformed(ActionEvent e) {model.put("As", "If");
}
JList EventsJList EventsJLists support the ListSelection event JLists support the ListSelection event notificationnotificationClients implement the Clients implement the ListSelectionListener interfaceListSelectionListener interface
void valueChanged(ListSelectionEvent e)void valueChanged(ListSelectionEvent e)A ListSelectionEvent knows several A ListSelectionEvent knows several thingsthings
first selected indexfirst selected indexlast selected indexlast selected indexgetValueIsAdjusting()getValueIsAdjusting()
JList Event ExampleJList Event Examplepublic class ExampleListListening extends JFrame implements ListSelectionListener {…ExampleListListening() {…JList aList = new JList(someModel);aList.addListSelectionListener(this);…
public void valueChanged(ListSelectionEvent e) {if (!event.getValueIsAdjusting()) {
String value = event.getSource().getSelectedValue();System.out.println(“Selection is “ + value);
}
}
}
List Cell RenderingList Cell RenderingJList gives you the option to display not JList gives you the option to display not just Strings, but graphical icons as welljust Strings, but graphical icons as wellYou need to create a new cell rendererYou need to create a new cell renderer
implement the ListCellRenderer interfaceimplement the ListCellRenderer interfaceset the custom text and icon (image) in this set the custom text and icon (image) in this classclass
JTableJTableJTable is a Tabular (row-column) view with JTable is a Tabular (row-column) view with read-only or editable cellsread-only or editable cellsCan create a JTable on:Can create a JTable on:
Two Arrays Two Arrays 2d array of data, 1d array of column headings2d array of data, 1d array of column headings
Two VectorsTwo Vectors(data of length row X columns), column (data of length row X columns), column headingsheadings
TableModel, (optionally) ListSelectionModel and TableModel, (optionally) ListSelectionModel and TableColumnModelTableColumnModel
Table ModelsTable ModelsTableModel is an TableModel is an interface that defines interface that defines the row/column the row/column behaviorbehavior
AbstractTableModel AbstractTableModel implements most of the implements most of the behaviorbehavioryou implement you implement getColumnCount(), getColumnCount(), getRowCount(), getRowCount(), getValueAt()getValueAt()
TableModel
getColumnCount( )getRowCount( )getValueAt( )isCellEditable( )
AbstractTableModel
JDBCAdapter YourTableModel
<<interface>>
Example Table ModelExample Table Modelpublic ExampleTableCustomModel() {
super();JTable table = new JTable(new CustomDataModel());createColumnHeadings(table);getContentPane().add(table.createScrollPaneForTable(table));
}
public void createColumnHeadings(JTable table) {String headers[] = {"Zero", "One", "Two", "Three", "Four"};table.setAutoCreateColumnsFromModel(false);for (int i=0; i<5; i++) {
TableColumn column = new TableColumn(i);column.setHeaderValue(headers[i]);table.addColumn(column);
}}
Example Custom ModelExample Custom Model
public class CustomDataModel extends AbstractTableModel {
/** * getColumnCount returns 0 since we will create columns ourselves */public int getColumnCount() { return 0;}
public int getRowCount() {return 5;}
/** * getValueAt is semi-bogus; it returns a string of row * column. */public Object getValueAt(int row, int col) {
return Integer.toString(row * col);}
}
Table SelectionTable SelectionThere are several selection attributes of There are several selection attributes of JTable you can setJTable you can set
setRowSelectionAllowed(boolean value)setRowSelectionAllowed(boolean value)setColumnSelectionAllowed(boolean setColumnSelectionAllowed(boolean value)value)setSelectionForeground(Color value)setSelectionForeground(Color value)setSelectionBackground(Color value)setSelectionBackground(Color value)
You can also turn horizontal and vertical You can also turn horizontal and vertical lines on and offlines on and off
List SelectionList SelectionJTables support ListSelection JTables support ListSelection notificationnotification
Clients must implement the Clients must implement the ListSelectionListener interfaceListSelectionListener interfaceJust like JLists in that respectJust like JLists in that respect
The Event doesn’t carry the necessary The Event doesn’t carry the necessary selection informationselection information
You need to query the table for selection You need to query the table for selection informationinformationUse getSelectedRow(), Use getSelectedRow(), getSelectedColumn(), getValueAt()getSelectedColumn(), getValueAt()
TableSelectionListener TableSelectionListener ExampleExample
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 TreesSwing TreesJTree is a hierarchical display componentJTree is a hierarchical display component
allows expansion, contraction, editing of allows expansion, contraction, editing of nodesnodes
JTree displays a TreeModelJTree displays a TreeModelTreeModel is built from TreeNodesTreeModel is built from TreeNodesMutableTreeNodes hold arbitrary objectsMutableTreeNodes hold arbitrary objects
TreeModel HierarchyTreeModel HierarchyTreeNode is an interface TreeNode is an interface that describes node that describes node behaviorbehaviorMutableTreeNode is an MutableTreeNode is an interface that allows interface that allows addition/removal of addition/removal of childrenchildrenDefaultMutableTreeNode DefaultMutableTreeNode implements implements MutableTreeNodeMutableTreeNode
TreeNode
getParent( )children( )getChildAt( )isLeaf( )
MutableTreeNode
remove(MutableTreeNode )insert(MutableTreeNode, int )setParent( MutableTreeNode)setUserObject(Object )
DefaultMutableTreeNodegetUserObject( )add( MutableTreeNode)
<<interface>>
<<interface>>
TreeNode ExampleTreeNode Examplepublic 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 SelectionTree SelectionJTrees support the TreeSelectionEvent JTrees support the TreeSelectionEvent notificationnotification
Clients must implement the Clients must implement the TreeSelectionListener interfaceTreeSelectionListener interfacevoid valueChanged(TreeSelectionEvent e)void valueChanged(TreeSelectionEvent e)
Use the JTree method getSelectionPath() Use the JTree method getSelectionPath() to get a TreePath that gives the to get a TreePath that gives the selection(s)selection(s)
Tree ExpansionTree ExpansionJTrees also support the JTrees also support the TreeExpansionEvent notificationTreeExpansionEvent notification
Clients implement TreeExpansionListenerClients implement TreeExpansionListenervoid treeExpanded(TreeExpansionEvent e)void treeExpanded(TreeExpansionEvent e)void treeCollapsed(TreeExpansionEvent e)void treeCollapsed(TreeExpansionEvent e)
You can ask the TreeExpansionEvent to You can ask the TreeExpansionEvent to getPath() and return the affected pathgetPath() and return the affected path
SummarySummarySwing is a comprehensive expansion and Swing is a comprehensive expansion and replacement for AWTreplacement for AWTYou've seen some basic and advanced You've seen some basic and advanced concepts in Swing Programmingconcepts in Swing Programming
More InformationMore InformationFor more information, see the Swing For more information, see the Swing tutorials on the Sun Java Developer's tutorials on the Sun Java Developer's Connection website Connection website (http://developer.java.sun.com) (http://developer.java.sun.com)
requires registration (free)requires registration (free)Steven Gutz, "Up to Speed With Swing, Steven Gutz, "Up to Speed With Swing, 2nd Edition", Manning, 20002nd Edition", Manning, 2000