Journal Articles
Browse in : |
All
> Journals
> CVu
> 133
(12)
All > Topics > Programming (877) Any of these categories - All of these categories |
Note: when you create a new publication type, the articles module will automatically use the templates user-display-[publicationtype].xt and user-summary-[publicationtype].xt. If those templates do not exist when you try to preview or display a new article, you'll get this warning :-) Please place your own templates in themes/yourtheme/modules/articles . The templates will get the extension .xt there.
Title: What Is Swing?
Author: Administrator
Date: 03 June 2001 13:15:46 +01:00 or Sun, 03 June 2001 13:15:46 +01:00
Summary:
Body:
"Swing" is the name of an Application Programming Interface for the Java platform. In a nutshell it is the project name for plugable look-and-feel graphical user interface. Swing is one fifth of Sun's Java division architecture for user interface design, better known as the Java Foundation Classes. Confused? You won't be if you can understand that this is just marketing between two large companies[1]. Simply put the JFC consists of the five parts: the Abstract Windows Toolkit (AWT), Accessibility, Java 2D, Drag and Drop, and Swing. Accessibility is the programming interface for the visually impaired and/or audio inhibited. Java 2D is an API for drawing, painting, rendering, and printing two-dimensional graphics. Drag and drop is another API for dragging and dropping data through a user interface. It compliments the cut and paste functionality. The AWT was the original user interface for first Java release and it is based on the native windows look-and-feel where systems calls are called to render the user interface. AWT is thus described as heavyweight user interface. Swing is a viable solution and is built on top of AWT, but the painting (rendering) of the user interface is done with Java primitives itself. In other words Java emulates the look-and-feel of the native platform (or platforms) without making use of the native systems call itself. All widgets in Swing are available on all platforms that Java runs whether the native system windows toolkit has this feature or not. Because Java virtual machine is rendering the user interface, this mode of emulation is called lightweight. The last advantage gives this technique an edge over other user interface solutions. Swing's lightweight architecture allows dynamic look-and-feels to be hot-swapped simultaneously as a Java application is running.
Before Swing was conceived all Java user interfaces where written with the limitations of the AWT, which caused problems of portability for pre-Swing applications, because the user interface would be different on one vendor's operating system to another. Another problem was one vendor's system would have a special widget that the other system did not have and vice versa. This meant that AWT is rather lacklustre, because it had to confirm to the most common denominator of widgets. (Incidentally AWT architecture is based on the BRIDGE software pattern where there is a Java component factory and a native component factory for each windows system.) In contrast Swing provides many more components than AWT. Additionally there is now a default standard look-and-feel for Java applications called Metal. So users and developer never need feel out of place wherever they choose run their programs, because Java Swing programs can emulate the operating system's native look and feel (provided the necessary the necessary plugable look and feel implementation has been written for it).
Swing provides a large set of components from a simple push button to a complex table component. It has much more functionality than the original "heavy" AWT. You simply import the necessary Java Swing package to get started using Swing. If you have the latest J2SE installed then it is included as standard. Here are the packages that are most important for this introduction.
Table 1. Important Java Packages for Swing
Package | Description |
---|---|
javax.swing | Contains the basic swingcomponents, default data model & utility classes |
javax.swing.border | Contains the classes & interfaces for decorating borders |
javax.swing.event | Contains all swing specific event types & borders |
javax.swing.table | Contains class & interfaces for Swing JTable components |
javax.swing.text | Contains class & interfaces for Swing text components |
javax.swing.tree | Contains class & interfaces for Swing JTree components |
The designers of Swing had the clever foresight to use a design pattern called the MODEL-VIEW-CONTROLLER (also known as MVC) in their architecture. This pattern solves a well-known user interface design problem. That is how to separate the presentation of the application from the business application logic. The business logic defines how the data is manipulated. In other word the model is maintaining the state and transaction of the data. Your application code belongs to the MODEL. The presentation is the responsibility of the user interface, and here is where Swing involved, it displays a representation of the data or displays a means of controlling the data. Therefore Swing provides you, the software developer, the ready-made CONTROLLER and VIEW. All you have to do is know how it works. Simple. So the controller is responsible for handling event-driven input or stimulus that ultimately affects the model. This is your keyboard, mouse or graphics tablet for instance. In computer science we call this input "the feel", because this is your sensory input. The "view" is responsible for the presentation of the data that exists in the model. The way information in the data model is rendered is called "the look".
The model, the view, the controller are not necessarily simple objects. They can be many objects in fact. You should think of them as separate entities that are loosely coupled together to form the design. The flexibility of the MVC is that each part of the architecture can be linked & changed with affecting the other parts. For instance my model might be database table and the view could be a component that displays that data as a table or a view that prints the table or a view that draws a pie chart of the data. The most of important is that the chosen type view does not affect the model. Likewise the model might be changed or improved algorithmically without interfering with the view (or views).
Swing is an adaptation of the MVC pattern, because it only provides two and one thirds bits of the whole part. The third remaining bit is the data model, which Swing defines in the most part as Java interfaces and/or abstract Java classes. Swing component, then, are very closely associated to a data model. The MVC architecture makes it easy to customise, inherit or replace a component's data model. Swing provides common data models such as a ButtonModel, ListModel, Document, TableModel and TreeModel for instance. A JButton, which is a simple push button component, is associated with a ButtonModel. A JTableModel, which is a complex table component, is associated with a TreeModel.
The "look-and-feel" of any Swing application is changeable at run-time. Swing performs this trick by defining plugable look-and-feel classes (PLAF). The PLAF emulates the native application windows LAF. There is a PLAF for Microsoft Windows, another one for Open Motif, and a generic PLAF called Metal. How does this work? Swing makes use of the BRIDGE pattern once again and ABSTRACT FACTORY through a technique called delegation. Every Swing component pushes the responsibility of rendering itself to a special class called a User Interface Delegate. Every PLAF provides versions of the UI delegate that render an emulation of the target LAF. So in the Windows PLAF there is a UI delegate that renders a JButton component in the windows appropriate style. The Motif PLAF has a UI delegate class that renders the same JButton component in the Open Motif toolkit style. And that ladies and gentleman is what Swing is really all about? It is flexible enough to emulate a native and feel without compromising the quality of professional and contemporary user interface design. You can really swing it.
Let us start programming in Swing. If you have programmed with the AWT, then switching to the new Swing interface is just a step up the ladder. Most AWT components can be changed into a Swing component by prefixing the capital letter "J". For instance an AWT java.awt.Button becomes a Swing javax.swing.JButton. Some of the accessor and mutator methods have changed, but that is what the JavaDoc is there for!
For this introduction I assume that you have some experience of AWT and the event delegation model that has been around since the JDK 1.1. Swing inherits many features from the AWT, but adds many new ones. You should also be familiar with the java.event.ActionEvent and java.event.ActionListener. Because I am not going to give you that same all "Hello Java Swing Applet" rubbish, rather we are going jump straight into a mock up Java application. Our first simple Swing application is a simple JFrame with two JList components and two JButtons. Initially the first list is full of data and the second is empty. The first button "add" allows you add one selected item in the first list to the other. The second button "remove" allows you remove one selected item from the second list. This preferences/configuration design is now so common now in many applications. I first saw it on the Apple Macintosh Finder, and it has been copied from one application, one operation system to another that it is you know what to do with your eyes wide shut.
Here is the code of the first Swing prototype application:
// File: PreferencesApp1.java import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; (1) public class PreferencesApp1 extends JFrame implements ActionListener { protected JButton bt_add, bt_remove, bt_quit; protected JList list_availableFont, list_configFont; public PreferencesApp1( String title ){ super(title); (2) GraphicsEnvironment lge = GraphicsEnvironment.getLocalGraphicsEnvironment(); String [] familyNames = lge.getAvailableFontFamilyNames(); (3) DefaultListModel availableModel = new DefaultListModel(); for ( int j=0; j<familyNames.length; ++j ) availableModel.addElement( familyNames[j] ); (4) DefaultListModel configModel = new DefaultListModel(); Container container = getContentPane(); container.setLayout( new BorderLayout( 1,1 ) ); (5) JLabel label = new JLabel("Swing Preferences App"); (6) label.setFont( new Font( "Arial", Font.BOLD, 18 ) ); label.setForeground( Color.black ); label.setBackground( Color.yellow ); label.setOpaque(true); container.add( label, BorderLayout.NORTH ); list_availableFont = new JList( availableModel ); (7) JScrollPane scroller_availableFont = new JScrollPane( list_availableFont ); container.add( scroller_availableFont, BorderLayout.WEST ); list_configFont = new JList( configModel ); (8) JScrollPane scroller_configFont = new JScrollPane( list_configFont ); container.add( scroller_configFont, BorderLayout.EAST ); Box box = Box.createVerticalBox(); (9) container.add( box, BorderLayout.CENTER ); bt_add = new JButton( "Add >" ); box.add( Box.createVerticalStrut( 50 )); (10) box.add( bt_add ); (11) bt_remove = new JButton( "Remove <" ); box.add( Box.createVerticalStrut( 5 )); box.add( bt_remove ); bt_quit = new JButton( "Quit" ); box.add( Box.createVerticalStrut( 25 )); box.add( bt_quit ); bt_quit.addActionListener(this); (12) } public void actionPerformed( ActionEvent evt ) { Object src = evt.getSource(); (13) if ( src == bt_quit ) { System.out.println( "Goodbye."); System.exit(0); } } public static void main( String [] args ) { PreferencesApp1 prefApp = new PreferencesApp1( "Prefences App Example"); (14) prefApp.setSize( new Dimension( 450, 400 ) ); prefApp.pack(); prefApp.setVisible( true ); } }
-
For this first Swing application we import the base Java Swing API classes (javax.swing.*) and also the AWT base and event classes (java.awt.*).
-
Notice first that the PreferencesApp1 class is subclassed from a Swing javax.swing.JFrame class instead of an AWT java.awt.Frame class. The window frame title parameter passed on directly to the superclass.
-
Here is a new feature class java.awt.GraphicsEnvironment of the Java 2D API to retrieve all the available font family names from the local graphics environment.
-
Now we create two list data models for our mini application. Swing provides a java.swing.ListModel, which is an interface class. It also provides a default implementation called javax.swing.DefaultListModel that look very similarly to the java.util.Vector class. (In fact there is a Vector object inside of it). We create one DefaultListModel and fill it with the font family names. We, then, create a second empty one, which will be the user's customised list.
-
All Swing components have a separate internal layered container called the Content Pane. Whereas with the AWT you added a Button component, say, directly to the Panel component. In Swing you cannot do this for Swing containers that are meant to manage other components. So we have to get an object reference to JFrame content pane component. Once we have the content pane then we set a new layout manager java.awt.BorderLayout for it.
-
Next, we can a JLabel component just for starters. We set the label's title, the font required, the foreground and the background colour. We also set the Jlabel so that it paints it own background fully with the setOpaque(true) method call. This is because JLabels do not normally render their backgrounds. (Another example of Swing's flexibility and lightweight philosophy). We add the new label to the frame's content pane positioned to the north.
-
We create the first javax.swing.JList component here and supply it with the availableModel default list model object that contains the list of font family names. Immediately afterwards we create a swing scrolling pane component javax.swing.JScrollPane and supply it with the JList that we just created. This will provide a scrollable list UI element. We add the scroll pane to the content pane to the container's left-hand side.
-
We create the second JList component here and supply it with the empty configModel default list model object that we created earlier. We also create another scroll pane for this JList and add the combination to the content pane, but this time, to the container's right-hand side.
-
Now for something especially unique to Swing. We create a special layout manager component javax.swing.Box that vertically lays out it children. In this Box component we will add the JButtons "Add", "Remove", and "Quit" to control the application. We add the Box centrally to the content pane.
-
Working with the Box we create JButton and give it a label title, then we simultaneously create and add a vertical strut of 50 pixels, which is a special component that keeps a rigid area no matter how the parent container resizes it. The strut is invisible component that does no rendering or painting, instead creates the illusion of space. NB: You can create horizontal struts too.
-
We add the first JButton "Add" to the Box container. We repeat the exercise for the remaining two JButtons.
-
Finally we at least register the PreferenceApp1 as an action listener to one JButton "quit", so we can stop the program.
-
This is the action listener method, which only operates on ActionEvents fired from the "quit" button. It will gracefully terminate the application.
-
Here is the main program where we create the PrefencesApp1 object and give it a set size, order it calculate the geometry with the pack() method call and make it visible to the display.
Finally, at the bottom of the next page there is miniature UML object diagram of some of the Swing and AWT classes. It should be enough to get you started with Swing and JFC. In the next article I add more functionality to this prototype. We will look at the list model in depth and complete action listener so those fonts can be added and removed from the configuration list. We will look at the content pane too. Enjoy.
http://java.sun.com/products/jfc/ Sun's product home page of the JFC
http://java.sun.com/products/jfc/whitepaper.html A white paper of the JFC philosophy
http://java.sun.com/products/jfc/tsc/ The Swing Connection Page
http://www.manning.com/Robinson/index.html Swing Book
http://www.algonet.se/~set_lo/java/sbe/ On line book Swing mirror in Sweden
http://www2.gol.com/users/tame/swing/examples/ SwingExamples.html Tamemasu Nobuo's brilliant Swing JFC examples with great screen shots (intermediate/advanced)
http://www.jguru.com/jguru/faq/faqpage.jsp?name=Swing jGuru excellent frequently asked questions on Swing.
Java 2D Graphics by Jonathan Knudsen, (1-56592-484-3), O'Reilly, 1st Edition May 1999, 355pp
Java Swing by Robert Eckstein, Marc Loy & Dave Wood, (1-56592-455-X), O'Reilly, 1st Edition September 1998, 1255pp
Swing by Matthew Robinson and Pavel Vorobiev, (1-8847-7784-8), Manning, December 1999, Softbound, 944pp
Notes:
More fields may be available via dynamicdata ..