CIS-257 Home: http://www.c-jump.com/bcc/c257c/c257syllabus.html
Java provides a rich set of user interface classes for creating interactive applications:
Abstract Window Toolkit (AWT)
Swing
Standard Widget Toolkit (SWT)
The original set of classes was called AWT, the Abstract Windowing Toolkit, but it has been replaced for the most part by the Swing classes.
The Java Foundation Classes (JFC or Swing) are a complete set of light-weight user interface components.
A rich graphical Java application can be developed using the Swing class library.
Swing is large (over 300 classes and interfaces) -- complex -- and a very large topic that is beyond the scope of our course...
...However, studying the architectural design of Java Swing library serves as an illustration of an industrial strength framework.
Many Swing classes represent all-familiar components that appear in a graphical application:
buttons, menus, text fields, lists, tables, trees, etc.
Associating a handler object with UI components attaches an action to be taken when the user clicks a button, etc.
The JFC package was called Swing during development.
It was intended to use the "JFC" name upon release.
However, the nickname Swing has stuck, leading Java programmers to say
"it's spelled JFC, but it's pronounced Swing."
JButton is an implementation of a push button.
Buttons can be decorated with text or a graphic icon.
JFrame is a top-level window with a captioned title and a border.
A frame is used to represent the application.
JLabel is a display area for a short length text string.
Labels are often used alongside input text areas to document their purpose.
JMenuBar represents a menu-bar as might appear at the top of a frame.
JPanel is a general-purpose container frequently used to group other components.
JTextArea is a multi-line text area for presenting plain text.
JTextField is a component that permits the editing of a single line of text.
JOptionPane.showInputDialog() gets input from the user
JOptionPane.showMessageDialog() displays a message box
All Swing components inherit from the JComponent class.
JComponent provides
Pluggable look and feel
Keystroke handling, including nested components
A border property
Tooltips that pop up when the mouse hovers over the component
Automatic scrolling support of any component that is placed in a scroller container.
Application windows inherit from JFrame class.
Applets inherit from JApplet class.
The JFrame.getContentPane( ) method returns the container where program can
add visible components
modify the layout.
For example,
JButton button = new JButton( "Hello" ); frame.getContentPane().add( button ); // add button to layout
// @topic T11615 Swing demo A1 // @brief Minimal JFrame and JButton example /* * @author ik * */ package pckg; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.text.*; public class SwingMain { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }//main public static void createAndShowGUI() { // Swing test JFrame frame = new JFrame("JFrame is me"); frame.setBounds(0, 0, 400, 300); JButton button = new JButton("Hello"); frame.getContentPane().add(button); // add button to layout frame.setVisible(true); } //createAndShowGUI } //SwingMain
Swing components implement 100% of their functionality in pure Java.
Swing components are referred to as lightweight components...
...they don't rely on native user-interface components, such as Windows buttons, Motif buttons, or Mac buttons.
Swing provides...
...image buttons, hover buttons, tooltips, tables, trees, splitter panels, customizable dialog boxes and quite a few other components.
Swing components make use of an architecture derived from the model-view-controller design pattern:
The model class stores the data.
The view class is responsible for rendition of the data on the screen.
The controller class makes changes in both the data and the view.
|
|
// @topic T11625 Swing demo A2 // @brief Minimal JFrame, JPanel and JButton example /** * @author ik */ package pckg; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.text.*; public class SwingMain { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }//main public static void createAndShowGUI() { // Swing test JFrame frame = new JFrame("JFrame is me"); frame.setBounds(0, 0, 400, 300); JPanel jpan = new JPanel(); frame.getContentPane().add(jpan); JButton jbut = new JButton("Hello"); jpan.add(jbut); frame.setVisible(true); } //createAndShowGUI } //SwingMain
|
|
// @topic T11635 Swing demo A3 -- OS-specific look and feel // @brief UIManager.getSystemLookAndFeelClassName( ) .setLookAndFeel( ) /** * @author ik */ package pckg; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.text.*; public class SwingMain { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }//main public static void createAndShowGUI() { // Swing test setSystemLookFeel(); JFrame frame = new JFrame("JFrame is me"); frame.setBounds(0, 0, 400, 300); JPanel jpan = new JPanel(); frame.getContentPane().add(jpan); JButton jbut = new JButton("Hello"); jpan.add(jbut); frame.setVisible(true); } //createAndShowGUI // Setting OS-specific look and feel: private static void setSystemLookFeel() { // Force GUI to come up in the OS-specific look and feel String laf = UIManager.getSystemLookAndFeelClassName(); try { UIManager.setLookAndFeel(laf); } catch (UnsupportedLookAndFeelException exc ) { System.err.println("Unsupported: " + laf); } catch (Exception exc) { System.err.println("Error loading " + laf); } }//setSystemLookFeel } //SwingMain
The system exit procedure is not called automatically when a user clicks on the close box X.
To enable expected behavior,
Add a WindowListener to the frame.
Catch the WindowClosing event.
This can be done most effectively by subclassing the WindowAdapter class as follows:
JFrame frame = new JFrame("JFrame is me"); frame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent ev) { System.exit(0); } } );
See next side for complete example.
// @topic T11645 Swing demo A4 -- Close Window Box // @brief JFrame.addWindowListener() JButton /** * @author ik */ package pckg; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.text.*; public class SwingMain { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }//main public static void createAndShowGUI() { // Swing test setSystemLookFeel(); JFrame frame = new JFrame("JFrame is me"); frame.setBounds(0, 0, 400, 300); frame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent ev) { System.exit(0); } } ); JPanel jpan = new JPanel(); frame.getContentPane().add(jpan); JButton jbut = new JButton("Hello"); jpan.add(jbut); frame.setVisible(true); } //createAndShowGUI // Setting OS-specific look and feel: private static void setSystemLookFeel() { // Force GUI to come up in the OS-specific look and feel String laf = UIManager.getSystemLookAndFeelClassName(); try { UIManager.setLookAndFeel(laf); } catch (UnsupportedLookAndFeelException exc) { System.err.println("Unsupported: " + laf); } catch (Exception exc) { System.err.println("Error loading " + laf); } }//setSystemLookFeel } //SwingMain
Alternatively, it is possible to set up a WindowAdapter-derived class independently:
Swing demo A5 uses sublassing main application frame named ApplicationFrame. The ApplicationFrame extends javax.swing.JFrame, and uses Dimension, JPanel, java.awt.event.WindowAdapter, JFrame.addWindowListener:
Class SwingMain: SwingMain.java (download)
Sequence diagram of window creation and closing:
The next step is to make the functionality of the JFrame reusable.
This can be done by extending the JFrame and adding appropriate initialization.
The following sample code demonstrates FrameApplication class added to application package, and Javadoc comments.
Swing demo A6 makes FrameApplication reusable:
Class SwingMain: SwingMain.java (download)
Class FrameApplication extends javax.swing.JFrame:
FrameApplication.java
(download)
The sequence diagram of window creation:
The sequence diagram of window closing:
Our next sample demonstrates a simple program with two buttons in a frame.
Change Color button changes the color of the background.
Quit button causes the program to exit.
Swing demo A7 creates GUI window with two buttons:
FrameApplication.java (download) extends javax.swing.JFrame
FrameTwoButtons.java (download) extends FrameApplication and implements ActionListener
Notice few more changes that took place in FrameApplication class:
Although setFrameDimension( ) remains, it is no longer invoked by the constructor, presuming that the derived class will do that.
The
JFrame.setVisible(true);
is now a responsibility of the FrameTwoButtons constructor.
Use with setBackground() and setForeground()
Provides named constants that represent 13 colors
Program can create custom Color object:
Color someColor = new Color( r, g, b );
where r, g, b are shades of each color; 0 represents the darkest and 255 represents the lightest shade
Program can also discover the red, green, or blue components of any existing color with getRed(), getGreen(), and getBlue()
The sequence diagram of window creation:
The sequence diagram of the button changing color:
The sequence diagram of the quit button:
The sequence diagram of window closing:
To add a component to a JFrame, we must use JFrame.contentPane( ).
In addition, JFrame maintains title, border, and optional menu bar.
By default, JFrame is displayed in the upper-left corner of the screen. To display window at specific location, use JFrame.setLocation(x,y) method.
See also: http://www.javabeginner.com/jframe.htm tutorial on the web.
To determine UI component position in a frame or a panel, a layout manager object is used.
There are several layout managers in Swing:
FlowLayout: default layout manager:
Adds UI components to the top of container, in left-to-right order.
If out of space, creates a new row of UI components.
By default, components are centered horizontally.
BorderLayout
GridLayout
To use a layout manager,
construct the layout, e.g.
new FlowLayout( FlowLayout.CENTER );
pass layout manager object to the JPanel.setLayout() method:
myPanel.setLayout( new FlowLayout( FlowLayout.CENTER ) );
call JPanel.add() method to add UI components:
myPanel.add( myButton );
BorderLayout class places swing components in the
NORTH, SOUTH, EAST, WEST and CENTER of a container.
Components are added by BorderLayout.add() method.
See also: http://www.javabeginner.com/java-swing/java-borderlayout-class-example tutorial on the web.
GridLayout class arranges swing components in tabular format:
// Use grid with 2 rows and one column: this.setLayout(new GridLayout(2, 1)); this.getContentPane().add(mRadioPanel); this.getContentPane().add(mMainPanel); this.pack(); // Auto-arrange frame layout
The following example demonstrates FrameRadioButtons class with two panels. GroupRadioButtons panel contains the radio buttons; another panel contains the push buttons, Change Color and Quit:
SwingMain.java (download) class SwingMain
FrameApplication.java (download) class FrameApplication extends javax.swing.JFrame
FrameApplicationClosing.java (download) class FrameApplicationClosing extends java.awt.event.WindowAdapter
FrameRadioButtons.java (download) class FrameRadioButtons extends FrameApplication implements ActionListener
GroupRadioButtonsListener.java (download) class GroupRadioButtonsListener implements ActionListener
GroupRadioButtons.java (download) class GroupRadioButtons extends JPanel, GroupRadioButtonsListener, JRadioButton, ButtonGroup, GridLayout, BorderFactory, Border
The sequence diagram of window creation:
The sequence diagram of clicking "blue" radio button:
The sequence diagram of the button changing color:
The sequence diagram of the quit button:
To create a menu,
Create a menu bar
Add top-level menus
Add menu items to each of the top-level menus.
JMenu mHelp; JMenuItem mHelpAbout; mBar = new JMenuBar(); // menu bar this.setJMenuBar(mBar); // add to JFrame mHelp = new JMenu("Help"); // top-level menu mBar.add(mHelp); // add to menu bar mHelpAbout = new JMenuItem("About"); mHelp.add(mHelpAbout); // sub-menu
Menus provide single click interface to initiate user actions.
JMenuItems generate corresponding ActionEvents.
Menu clicks cause events to be generated.
As with push buttons, program uses action listeners to hook each JMenuItem.
mFileExit.addActionListener(mMenuFileExitListener);
where mMenuFileExitListener is an object that extends javax.swing.AbstractAction class.
The following example demonstrates FrameRadioButtons class with radio buttons and menu:
SwingMain.java (download) class SwingMain
FrameApplication.java (download) class FrameApplication extends javax.swing.JFrame
FrameRadioButtons.java (download) class FrameRadioButtons extends FrameApplication implements ActionListener
FrameApplicationClosing.java (download) class FrameApplicationClosing extends java.awt.event.WindowAdapter
GroupRadioButtons.java (download) class GroupRadioButtons extends JPanel
GroupRadioButtonsListener.java (download) class GroupRadioButtonsListener implements ActionListener
MenuFileExitListener.java (download) class MenuFileExitListener extends javax.swing.AbstractAction
The only working menu item in this demo is
File -> Exit
The sequence diagram of window creation:
The sequence diagram of clicking File -> Exit menu:
A dialog window opens apart from the main Swing Application Window.
Dialogs provide independent sub-windows to display
a message box (e.g. "Okay to proceed? YES/NO", etc.)
an open/save file (standard file dialogs)
a customized dialog (e.g. tabbed dialog with options)
print dialogs, etc.
See also How to Make Dialogs tutorial on java.sun.com website.
This sample consolidates push buttons and menu clicks listener into a single method named FrameRadioButtons.actionPerformed.
Swing demo A10 creates GUI window with radio buttons, menus, and dialogs.
File -> Open menu demonstrates JFileChooser
View -> Options menu opens a tabbed dialog window.
SwingMain.java (download) class SwingMain
FrameApplication.java (download) class FrameApplication extends javax.swing.JFrame
FrameRadioButtons.java (download) class FrameRadioButtons extends FrameApplication implements ActionListener
FrameApplicationClosing.java (download) class FrameApplicationClosing extends java.awt.event.WindowAdapter
GroupRadioButtons.java (download) class GroupRadioButtons extends JPanel
GroupRadioButtonsListener.java (download) class GroupRadioButtonsListener implements ActionListener
DialogViewOptions.java (download) class DialogViewOptions extends JDialog implements ActionListener, PanelWithTabs
PanelWithTabs.java (download) class PanelWithTabs extends JPanel, JLabel. JTextField
The sequence diagram of window creation:
The sequence diagram of clicking View -> Options menu:
The sequence diagram of clicking OK button on the dialog window:
The sequence diagram of clicking Cancel button on the dialog window:
The sequence diagram of clicking "orange" radio button:
The sequence diagram of the button changing color:
The sequence diagram of clicking X button on the titlebar: