CIS-75 Home http://www.c-jump.com/CIS75/CIS75syllabus.htm
Java provides a rich set of user interface classes for creating interactive applications.
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
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.
Create directory
C:\CIS75
on your harddrive.
Download sample code for this week, Source.zip , and unzip it inside C:\CIS75.
If you are using Windows operating system, download file bin.zip and unzip inside C:\CIS75 likewise.
Examine the file
C:\CIS75\bin\config.bat
Most likely, it is necessary to edit the config.bat on your local machine. This is windows batch file that creates CIS-75 environment variables necessary to compile and run Java samples. The settings should match installed JDK version on your computer.
Once CIS-75 configuration paremeters are taken care of, navigate to the source subdirectory:
C:\CIS75\Source
Each sample contains Java files and batch files to execute the following tasks:
_clean.bat...........Delete previously compiled class files _compile.bat.........Compile Java source files _javadoc.bat.........Generate javadocs _run.bat.............Run the application _trace_insert.bat....Insert trace statements into the source code _trace_display.bat...Display sequence diagram generated by the trace
Double-click on any batch file to execute the corresponding action.
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.
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
For complete example see A1/application/SwingMain.java ( download ) sample program.
// Minimal JFrame and JButton example import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.text.*; public class application/SwingMain { public static void main(String args []) { // 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); } //main } //application/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.
|
|
For complete example see A2/application/SwingMain.java ( download ) sample program.
// Minimal JFrame, JPanel and JButton example import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.text.*; public class application/SwingMain { public static void main(String args []) { // 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); } //main } //application/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 complete sample A4/application/SwingMain.java ( download ).
Alternatively, it is permissible to set up a WindowAdapter-derived class independently:
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
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.
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 FrameTwoButtons constructor.
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:
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:
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.
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 menus:
A9/application/FrameRadioButtons.java ( download ). The only working menu item in this application is File -> Exit.
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
The sample consolidates push buttons and menu clicks listener into one single method named FrameRadioButtons.actionPerformed.
File -> Open menu demonstrates JFileChooser
View -> Options menu opens a tabbed dialog window.
A10/application/FrameRadioButtons.java ( download ) - main application window opens custom dialog when the user clicks View -> Options menu.
A10/application/DialogViewOptions.java ( download ) - custom dialog class that derives from JDialog.
A10/application/PanelWithTabs.java ( download ) - class that creates a JTabbedPane object with 3 tabs and other visible UI controls.