Previous |
Next |
Using the graphical components to create fully fledged Java applications is a complex task. I have several large books that specialize explicitly in the Swing libraries only. In particular I can recommend the Definitive Guide to Swing by John Zukowskii ISBN: 1590594479. There have been debates throughout the history of Java as to if the GUI capabilities are adequate for desktop applications. Much of this boils down to speed of start-up. Fortunately much of these concerns have been addressed by Moores law which says that the performance of CPU chips doubles every year and a half whilst the price halves.
http://en.wikipedia.org/wiki/Moore's_law
In the early days of Swing, the start-up time did seem excessive and sometimes the response was sluggish, but on any computer made today performance should be more than acceptable. The upcoming version of Java called Mustang (AKA JDK 1.6) is promising significant overall performance increases that will enhance the usability of swing applications. To see an example of a “real world” useful Java Swing application take a look at the Azureus Bit tTorrent applicaiton. Bit torrent is a fascinating way of distributed file sharing. You can download it at http://azureus.sourceforge.net/
Text fields are a basic ingredient of a wide range of applications. For example database applications where a user keys information into text fields which is then written to and from the database. The following code creates a form that contains two labels with associated text fields and a Submit button. To keep things simple I have omitted any event handling code.
import javax.swing.*;
import java.awt.*;
/**
*@author Marcus Green
*Demonstration of use of Java Swing Components
**/
public class Components extends javax.swing.JFrame{
public static void main(String argv[]){
new Components();
}
Components(){
/* GridLayout with 3 rows and 1 column */
GridLayout gl = new GridLayout(3,1);
setLayout(gl);
/**
*JPanel defaults to a Flow Layout and
*so components added will have their
*preferred size respected
**/
JPanel jpRow1 = new JPanel();
JPanel jpRow2 = new JPanel();
JPanel jpRow3 = new JPanel();
JLabel jlFirstName = new JLabel("First Name");
/** JTextField takes the number of
*columns (width) as a constructor paramter
**/
JTextField jtFirstName = new JTextField(20);
JLabel jlLastName = new JLabel("Last Name");
JTextField jtLastName = new JTextField(20);
/* add the components to the panel */
jpRow1.add(jlFirstName);
jpRow1.add(jtFirstName);
/* add the panel to the row within the GridLayout */
add(jpRow1);
jpRow2.add(jlLastName);
jpRow2.add(jtLastName);
add(jpRow2);
JButton jbSubmit = new JButton("Submit");
jpRow3.add(jbSubmit);
add(jpRow3);
/* Set the overall Frame size */
setSize(300,300);
/* Without this the application will be invisible */
setVisible(true);
}
}
The following screen shot shows how the application appears at runtime.

Note that if you resize the application and make the Form narrower, the labels will wrap so they appear above the associated text fields.
Creating menus is Java applications is relatively easy using a combination of the JmenuBar, Jmenu and JmenuItem classes. Note that in a real system you would not have the names of menus embedded within the code, but separated out as a resource to allow easy internationalisation. I have included sample code to allow this application to respond when the exit option is selected.
/**
*@author Marcus Green
*Demonstration of creating
*a menu bar with menues
**/
import java.awt.event.*;
import javax.swing.*;
public class MenuDemo extends JPanel{
public static void main(String argv[]){
new MenuDemo();
}
MenuDemo(){
JFrame frame = new JFrame("Menu Demo");
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem jmOpen = new JMenuItem("Open");
JMenuItem jmExit = new JMenuItem("Exit");
fileMenu.add(jmOpen);
fileMenu.add(jmExit);
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
frame.setSize(300,300);
frame.setVisible(true);
}
}
Illustration
1: Menu Demo
You can listen to menu events in the same way you would to other events such as the click of a button. You need to create an ActionListener class an attach it to the item using the add method. The following code demonstrates this.
/**
*@author Marcus Green
*Demonstration of attaching
*a listener to a menu item.
**/
import java.awt.event.*;
import javax.swing.*;
public class MenuDemo extends JPanel{
public static void main(String argv[]){
new MenuDemo();
}
MenuDemo(){
JFrame frame = new JFrame("Menu Demo");
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem jmOpen = new JMenuItem("Open");
/* this attaches the listener to the menu item */
jmOpen.addActionListener(listener);
JMenuItem jmExit = new JMenuItem("Exit");
jmExit.addActionListener(listener);
fileMenu.add(jmOpen);
fileMenu.add(jmExit);
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
frame.setSize(300,300);
frame.setVisible(true);
}
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
/*the value returned from getActionCommand
* can be used to work out what item was
* selected
*/
System.out.println("Menu item [" + event.getActionCommand( ) +
"] was pressed.");
}
};
}

The following code will add a shortcut keystroke combination to the Open menu item.
jmOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
Note that this acts as if the menu has been pressed but does not actually highlight the menu. If you test it within the code you will see it generates the event and the output will indicate the open menu option was selected. Only menu items that do not bring up others (leaf items) can have an accelerator associated.
To select a root menu and get it highlighted you can use the setMnemonic (memory jerker). Thus the following code will cause the File menu to be selected when Ctrl-F keystroke combination is selected. Note this doesn't generate an event action.
fileMenu.setMnemonic(KeyEvent.VK_F);
A separator bar can be added to a menu by using the addSeparator() method of the JmenuItem class. Thus the previous code can be modified as follows.
fileMenu.add(jmOpen); fileMenu.addSeparator(); fileMenu.add(printMenu); fileMenu.addSeparator(); fileMenu.add(jmExit);
Submenus or leaf menus can be added using the add method thus.
JMenuItem jmPrint1 = new JMenuItem("Option1");
JMenuItem jmPrint2 = new JMenuItem("Option2");
printMenu.add(jmPrint1);
printMenu.add(jmPrint2);
Here is the full code for a version of MenuDemo that uses separator and has a leaf menu under the print option.
/**
*@author Marcus Green
*Demonstration of attaching
*a listener to a menu item, using
*listeners, mnemonics and accellerator
*keys.
**/
import java.awt.event.*;
import javax.swing.*;
public class MenuDemo2 extends JPanel{
public static void main(String argv[]){
new MenuDemo2();
}
MenuDemo2(){
JFrame frame = new JFrame("Menu Demo");
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu printMenu = new JMenu("Print");
JMenuItem jmOpen = new JMenuItem("Open");
JMenuItem jmPrint1 = new JMenuItem("Option1");
JMenuItem jmPrint2 = new JMenuItem("Option2");
printMenu.add(jmPrint1);
printMenu.add(jmPrint2);
/* this attaches the listener to the menu item */
jmOpen.addActionListener(listener);
JMenuItem jmExit = new JMenuItem("Exit");
jmExit.addActionListener(listener);
fileMenu.add(jmOpen);
fileMenu.addSeparator();
fileMenu.add(printMenu);
fileMenu.addSeparator();
fileMenu.add(jmExit);
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
frame.setSize(300,300);
frame.setVisible(true);
fileMenu.setMnemonic(KeyEvent.VK_F);
jmOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.ALT_MASK));
}
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
/*the value returned from getActionCommand
* can be used to work out what item was
* selected
*/
System.out.println("Menu item [" + event.getActionCommand( ) +
"] was pressed.");
}
};
}
T
he
swing Jbutton is a “lowest common denominator” control
that can be used for a wide variety of purposes. The Jbutton control
can display either text or a graphic. The following code shows a very
basic
Java supports the idea of anonymous class instances. As the name implies these are instances that are have no name, which raises the question that if they have no name how can you refer to them? The answer is that that they are created and used in the same part of the program and thus you don't need to give them a name. Personally I don't like anonymous classes at all, I find that they add to the complexity of code resulting in semi colons, parenthesis and curly braces in rather unexpected places.
People who like anonymous classes sometimes suggest that they represent more compact code, but for me the compactness is at the price of readability . find I never quite get the code right first time and when creating the following code I created a named class first and then modified it to be anonymous. The reason you should be aware of anonymous classes is that other programmers use them and it is common for GUI building tools to create them. The following code is a simple demonstration of the button object that sends output to the console when the button is clicked. I strongly recommend that you attempt to write your own example of an anonymous listener so you get an idea of how they are constructed and used.
/** Button Demo
* @author Marcus Green
* anonymouse event listeners
*/
import java.awt.event.*;
import javax.swing.*;
public class ButtonDemo extends JFrame{
public static void main(String argv[]){
ButtonDemo bd = new ButtonDemo();
bd.go();
}
public void go(){
JButton button = new JButton("Hello");
this.add(button);
setSize(100,100);
setVisible(true);
/* creating an anonymous instance of
* ActionListener */
button.addActionListener(
new ActionListener(){
public void actionPerformed (ActionEvent event){
System.out.println("click");
}
});
}
}
Like any high quality Graphical User Interface a Java button can display an image or icon on a button and “ToolTipText” that displays when the mouse hovers over the button. To make it easier for Java applications to have a similar look and feel Sun makes a set of graphical icons available in gif file format which you can incorporate into your applications. These icons can be found at
http://java.sun.com/developer/techDocs/hi/repository/index.html
The following is code creates a button with an icon by using the image icon class and adds tooltip text to the button.
/** Button Demo
* @author Marcus Green
* Buttons with graphics
* and tooltip text
*/
import java.awt.event.*;
import javax.swing.*;
import javax.swing.ImageIcon;
public class IconButton extends JFrame{
public static void main(String argv[]){
IconButton ib = new IconButton();
ib.go();
}
public void go(){
ImageIcon icon = new ImageIcon("Stop24.gif");
JButton button = new JButton("Hello",icon);
/**
*tooltip text displayed when the mouse
*hovers over the btton
*/
button.setToolTipText("A stop button");
this.add(button);
setSize(200,200);
setVisible(true);
}
}

Most desktop applications need the functionality to open and save files and the JFileChooser class offers this functionality. The following code shows the very basics of the functionality of this class.
/**
*@author Marcus Green
*demonstrating the JFileChooser
*dialog. In a real program
*the dialog would be called
*from a menu using event trapping
**/
import java.io.*;
import javax.swing.*;
public class FileChoose extends JPanel{
public static void main(String argv[]){
new FileChoose();
}
FileChoose(){
JFrame frame = new JFrame("FileChoose");
JFileChooser fc = new JFileChooser();
/* frame will be the parent of the dialog
*This does not return until the dialog
*is closed */
fc.showOpenDialog(frame);
File selFile = fc.getSelectedFile();
/*Show the save dialog*/
fc.showSaveDialog(frame);
frame.setSize(300,300);
frame.setVisible(true);
}
}
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JFileChooser.html
http://javaalmanac.com/egs/javax.swing.filechooser/CreateDlg.html

http://java.sun.com/docs/books/tutorial/uiswing/components/button.html#abstractbutton
The JEditorPane component allows you to embed a mini “word processor” into your applications that allows modification of HTML, RichText or plain text. The RichText format is a fairly large subset of the capabilities of a full word processing system so there is not much you cannot do with the JeditorPane. The JeditPane is most commonly used for displaying HTML, and the following example shows how it can load in the contents of a web page with a minimal amount of code.
/**
*@author Marcus Green
*using the JEditorPane to
*load in the contents
*of a remote web page
**/
import javax.swing.*;
import java.io.*;
public class Edit extends JFrame{
public static void main(String argv[]){
new Edit();
}
Edit(){
String url = "http://www.examulator.com/tamer";
try{
JeditorPane jed = new JEditorPane(url);
add(jed);
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
setSize(300,300);
setVisible(true);
}
}
Illustration
2: Screen shot of Edit
API docs for JEditorPane
http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JEditorPane.html
Marty Hall on JEditorPane
http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JEditorPane.html
The JscrollPane component provides a scrollable view of another swing component. Much of the work of the JscrollPane component happens “behind the scenes”. In the following code the Jtext area starts off with a horizontal scrollbar allowing the user to scroll left and right but it has no vertical scroll bar. If you start to type enough text and keep hitting return, eventualy a vertical scroll bar will show up.
/**
* showing the JScrollPane component
*@author Marcus Green
**/
import javax.swing.*;
public class Scroll extends JFrame{
public static void main(String argv[]){
new Scroll();
}
Scroll(){
JPanel jp = new JPanel();
JTextArea jte = new JTextArea();
jte.setText("This should force the scroll panel to show");
jte.setColumns(10);
JScrollPane scrollPane = new JScrollPane(jte);
add(scrollPane);
setSize(200,200);
setVisible(true);
}
}

Other sources
The Java API on
JscrollPane
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JScrollPane.html
The Sun Swing tutorial on Menus
http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
Previous |
Next |