1. Menus, Toolbars and Dialogs
1.1 Creating Menus
The JFrames we have created so far only have a title bar as shown below (left). However a usual application main frame should look like the one on the right
Creating a menu bar and menus on it is very easy. You simply use the JMenuBar constructor to create an menu bar instance, use theJMenu constructor to create the menus you need and then add the menu onto the menu bar, finally use JFrame’s setJMenuBarmethod to add the bar into the frame. The frame is created by the following code.
import javax.swing.*;
public class TestMenus {
public static void main( String[] argv ) {
JFrame myframe = new JFrame("My First Frame");
JMenuBar jmb = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenu helpMenu = new JMenu("Help");
jmb.add(fileMenu);
jmb.add(editMenu);
jmb.add(helpMenu);
myframe.setJMenuBar(jmb);
myframe.setSize(400, 300);
myframe.setLocationRelativeTo(null);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setVisible(true);
}
}
Nothing is more complicated than creating a JButton.
You can add menu items, separators, and submenus to the menu object. Suppose that the above editMenu has menu items Cut, Copy, Paste and a submenu Options with its own menu items Read-only, Insert, Overtype etc. Also there are several separators to groups menu items. See the frame below
To get this frame you only need put the following code before jmb.add(fileMenu) in the above program
JMenuItem cutItem = new JMenuItem("Cut");
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem pasteItem = new JMenuItem("Paste");
JMenu optionsMenu = new JMenu("Options");
JMenuItem readItem = new JMenuItem("Read-only");
JMenuItem insertItem = new JMenuItem("Insert");
JMenuItem overtypeItem = new JMenuItem("Overtype");
optionsMenu.add(readItem);
optionsMenu.addSeparator();
optionsMenu.add(insertItem);
optionsMenu.add(overtypeItem);
//Submenu done
editMenu.add(cutItem);
editMenu.add(copyItem);
editMenu.add(pasteItem);
editMenu.addSeparator();
editMenu.add(optionsMenu); //add a submenu
Actually you follow the same logic when you create menus, menu items and submenus.
1.2 Decorating Menu Items
You can create a check box or radio button menu item. You simply use for example
helpMenu.add(new JCheckBoxMenuItem(“Check it”));
helpMenu.add(new JRadioButtonMenuItem(“Check it”));
You can specify an image icon with the JMenuItem(String, Icon) to set an icon for the menu item, for example
JMenuItem cutItem = new JMenuItem(“Cut”, new
ImageIcon(‘cut.jpg”));
Similarly you can set a keyboard mnemonics for a menu item. For example
fileMenu.setMnemonic(‘F’);
then there is a underline below “F” in the menu “File” and the user can use ALT+F to choose the menu item or choose the submenu.
1.3 Creating Popup Menus
A pop-up menu is a menu that is not attached to a menu bar but that floats somewhere. You create a pop-up menu similarly to the way you create a regular menu. Unlike the regular menu bar that is always shown at the top of the frame, you must explicitly display a pop-up menu by using the show method. You specify the parent component and the location of the pop-up, using the coordinate system of the parent. For example
JPopupMenu popup = new JPopupMenu();
//creating menu items and add them it the popup menu
popup.show(aParentComponent, x, y);
Read Section 38.3 for more details.
1.4 Creating Toolbars
A toolbar is a button bar that gives quick access to the most commonly used commands in a program. Unlike the menu bar, you can drag the toolbar to elsewhere. When you release the mouse button, the toolbar is dropped into the new location.
Open your JCreator program, on the main window, you can see the toolbar which is just below the menu bar. On the toolbar you can find buttons for creating new files, cutting and pasting, even a combo box etc.
Toolbars are straightforward to program. First you create an tool bar instance with the JToolBar constructor
JToolBar mytoolbar = new JToolBar();
Then consider mytoolbar as a panel (or a container). You can simply add other components like JButtons, Combo Boxes etc into the tool bar object. Nothing is new.
The JToolBar class also has a method to add an Action object into the bar.
You can also separate groups of buttons in the bar with a separator:
mytoolbar.addSeparator();
Then there is a small gap between button groups.
By default, toolbars are initially horizontal. To have a toolbar start out as vertical, sue
JToolBar Mytoolbar = new JToolBar(JToolBar.VERTICAL);
After you have completed your toolbar design, you simply add it to a frame the same as you do for any components.
Read the program in Listing 38.3
1.5 Event Processing Events from Menu and Tool Bar
The menu items generate ActionEvent. You must implement the ActionListener interface’s the actionPerformed method to handle the event from the menu items. Of course you need to register your ActionListener with the menu item so the listener will respond to the menu selection.
The commonly added items on a tool bar are buttons. So you process the events from a tool bar in the similar way you handle with the button’s ActionEvent. Nothing is special.
Often menus and tool bars contain some common actions. For example, on the JCreator’s main window, you can save a file by choosing the File menu then Save menu item, or by quickly clicking the save button in the tool bar. In this case you need to register the sameActionListener to the menu items and button on a tool bar. To use a uniform way, Java offers the Action interface.
Read Section 34.5 but focus on what an Action is, how to create an action, how to install an action to menus and toolbars.
2. Dialog Boxes
So far, all our user interface components have appeared inside a frame window. However we usually want separate dialog boxes to pop-up to give a warning if the user is doing wrong thing with the program or to get information from the user.
Swing provides several kind of useful dialog boxes for the purpose. The JOptionPane has four static methods to show these simple dialogs: showMessageDialog, showConfirmDialog, showOptionDialog and showInputDialog
2.1 Message Dialogs
The simplest dialog box is the message dialog which is used to display a message with a OK button to alert the user and wait for the user’s action.
To show a message dialog, you can use one of three versions of the showMessageDialog method. Read the information on pages 1189-10 (8E) or java Swing document.
Test the following program
import javax.swing.*;
public class TestMessageBox {
public static void main( String[] argv ) {
JOptionPane.showMessageDialog(null, new String("This is a
Warning"), "Warning", JOptionPane.ERROR_MESSAGE);
}
}
- Change the ERROR_MESSAGE to INFORMATION_MESSAGE, PLAIN_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE.
- Change new String(“This is a Warning”) to another object for example new JButton(“Button!”)
2.2 Confirmation Dialogs
A message dialog box displays a message and waits for the user to click the OK button to dismiss the dialog. The method does not return any value. A confirmation dialog usually presents a question with up to three buttons for the user to choose one from. The confirmation dialog box is created by the JOptionPane’s method showConfirmDialog. The method will return an integer to indicate which button the user chose. Then the program can respond to it.
Read the following example
import javax.swing.*;
public class TestMessageBox {
public static void main( String[] argv ) {
int selection = JOptionPane.showConfirmDialog(null,
"Message", "Title", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (selection == JOptionPane.CANCEL_OPTION)
JOptionPane.showMessageDialog(null, new String("The
user chose the OK button"), "USER'S CHOICE",
JOptionPane.PLAIN_MESSAGE);
}
}
2.3 Input Dialogs
An input dialog box is pop-uped and used to receive input from the user. The box is created by call the showInputDialog method and the method will return the user’s input or choice.
With the method, you can specify a text field for the user to input, or specify a list of items for the user to choose from. Here is an example
String text = JOptionPane.showInputDialog(null, “Enter something:”, “InputDialog Demo”, JOptionPane.QUESTION_MESSAGE);
2.4 Options Dialogs
Unlike the confirmation dialog boxes with up-to three options, you can custom the number of options (buttons) with an option dialog. Here is an example and it is self-explanatory
int val = JOptionPane.showOptionDialog(null, “Make a choice”,
“Options”, JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE, null, new Object[] {“Choice 0”,
“Choice 1”, “Choice 2”, “Choice 3”}, “Choice 2”);
3. File Dialogs
In most of application software like MS Word, when you choose the File menu then the Open items you are presented in dialog window from which you can browse your file system to choose the file you want to edit. The pop-up window is called a File dialog in Java.
3.1 The JFileChooser class
To get such a window for your application, you can use the JFileChooser class to display a file dialog window similar to the one you use in MS Word.
Under the JFileChooser, you call the showOpenDialog to display a dialog for opening a file or you call the showSaveDialog to display a dialog for saving a file. The button for accepting a file is then automatically labeled Open or Save. Of course, you can change the label to anything you like with the general showDialog method.
Here are the steps needed to put up a file dialog box and recover what the user chooses from the box
- Make a JFileChooser object
JFileChooser mychooser = new JFileChooser();
- Set the directory with the setCurrentDirectory method as the starting point in the file system. Most of time you should set it to the current working directory
mychooser.setCurrentDirectory(new File(“.”));
- Show the dialog box by call the showOpenDialog or showSaveDialog method. You must supply the parent component in these calls
int result = chooser.showOpenDialog(parent);
The return value is JFileChooser.APPROVE_OPTION,
JFileChooser.CANCEL_OPTIION, or JFileChooser.ERROR_OPTION
- If the return value is JFileChooser.APPROVE_OPTION, then you can get the chosen file name and path by
String filename = chooser.getSelectedFile().getPath();
3.2 The File Filter
For example, when you want to open a file in MS Word, the file open dialog window will only display the files with extension name .docand .dot etc. To achieve this purpose, you can create a FileFilter first, then set the filter to the JFileChooser. For example if we are going to filter all the files with extension .doc, we can create a file filter in this way
public class DocFilter extends FileFilter {
public Boolean accept(File f) {
return f.getName().toLowerCase().endsWith(“.doc”) ||
f.isDirectory();
}
public String getDescription() {
return “Word Document”;
}
}
Then you can set a filter object to the JFileChooser
mychooser.setFileFilter(new DocFilter());
Check the following code and run it
import javax.swing.*;
import java.io.*;
import javax.swing.filechooser.FileFilter;
public class TestFileChooser {
public static void main( String[] argv ) {
JFrame myframe = new JFrame("Test File Chooser");
myframe.setSize(400, 300);
myframe.setLocationRelativeTo(null);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setVisible(true);
JFileChooser chs = new JFileChooser();
chs.setCurrentDirectory(new File("."));
chs.setFileFilter(new DocFilter());
int result = chs.showOpenDialog(myframe);
}
}
class DocFilter extends FileFilter {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".doc") ||
f.isDirectory();
}
public String getDescription() {
return "Word Document";
}
}
4. JTrees
You should be familiar with the visualized tree structures. For example, the Window systems File Manager display the file system as a tree structure of folders, see the left box on the figure below,
This kind of visual structure can be easily created with the assistance of the JTree class in Swing.
JTree is a Swing component that displays data in a treelike hierarchy. The subtrees on the structure can be collapsed or expanded. For example, in the above figure the Dev-Cpp is collapsed, so you cannot see the subfolders of the Dev-Cpp folder, while the Documents and Settings is expanded and its subfolders are displayed.
4.1 Tree terminology
A tree is composed of nodes. There is only one node called the root. Each node is either a leaf node or it has child nodes. Every node exception of the root has exactly one parent. Every one node plus its children, children’s children make up a subtree.
4.2 The JTree classes
The JTree class has seven constructors, please consult to Figure 40.20 for more details. To construct a default tree, you simply use
JTree tree1 = new JTree();
which create the following tree structure
You can create a tree from an array of Objects such as String.
JTree tree2 = new JTree(new String[] {“Appel”, “Orange”,
“Banana”, “Pear”});
which creete a tree with an invisible root and the elements simply as its children. If you want to see the root, you need usesetRootVisible(true).
Try the following program
import javax.swing.*;
import java.awt.*;
public class TestTree {
public static void main( String[] argv ) {
JFrame myframe = new JFrame("Test File Chooser");
myframe.setSize(400, 300);
JTree jTree1 = new JTree();
JTree jTree2 = new JTree(new String[] {"Appel", "Orange", "Banana", "Pear"});
jTree2.setRootVisible(true);
myframe.add(jTree1,BorderLayout.NORTH);
myframe.add(jTree2,BorderLayout.CENTER);
myframe.setLocationRelativeTo(null);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setVisible(true);
}
}
4.3 The TreeModel
If you have tried the last example, you would see the structure of both trees are quite simple with one root and one level of children. This kind of structural information is contained the TreeModel in which TreeNode stores and manages the tree data, like the labels in the last example.
If you want to get the root of an JTree instance, you first need to get the TreeModel of the tree by the getModel() method, then use thegetRoot method of the model. For example
TreeModel model = jTree1.getModel();
model.getRoot();
From the root, you can get its i-th children by
model.getChild(root, i);
After you have got one of children, consider it as the new root and then you can get this child’s children. The program in Listing 40.13 shows you how to access all the children in a tree.
4.4 The TreeNode Interface
Each node in a tree is represented by TreeNode which storing information of the node. One of the implementation for the TreeNode interface is the DefaultMutableTreeNode class.
With DefaultMutableTreeNode you can build a series of nodes and pack them in a single node. You build up your tree through nodes, you always begin with the leaf nodes. Let us build a JTree for the following actual tree.
For each leaf node, construct a DefaultMutableTreeNode
DefaultMutableTreeNode darlinghabour = new
DefaultMutableTreeNode(“Darling Habour”);
DefaultMutableTreeNode melbourne = new
DefaultMutableTreeNode(“Melboune”);
DefaultMutableTreeNode beijing = new
DefaultMutableTreeNode(“Beijing”);
DefaultMutableTreeNode pudong = new DefaultMutableTreeNode(“Pu Dong”);
DefaultMutableTreeNode huangpu = new DefaultMutableTreeNode(“Huang
Pu”);
Now create a default tree node for Sydney
DefaultMutableTreeNode sydney =
new DefaultMutableTreeNode(“Syndey”);
As the Darling Habour is a children of the Sydney, so we add the darlinghabour node into the sydney node
Sydney.add(darlinghabhour);
Then create a node for Shanghai and add both pudong and huangpu to it
DefaultMutableTreeNode shanghai = new
DefaultMutableTreeNode(“Shanghai”);
shanghai.add(pudong);
shanghai.add(huangpu);
Then add the syndey and melbourne nodes to australia node by
DefaultMutableTreeNode australia = new
DefaultMutableTreeNode(“Australia”);
australia.add(sydney);
australia.add(melbourne);
Add the beijing and shanghai nodes to china node
DefaultMutableTreeNode china =
new DefaultMutableTreeNode(“China”);
china.add(beijing);
china.add(Shanghai);
Finally add the australia and china nodes to the world
DefaultMutableTreeNode world =
new DefaultMutableTreeNode(“World”);
world.add(australia);
world.add(china);
Now we have packed all the information about the tree nodes and their relations in the node world, finally create the JTree by
JTree World = new JTree(world);

Can you put all the code together to create the tree in a program?
5. JTables
The JTable component displays a two-dimensional grid of objects, like a spreadsheet. Of course, tables are common in user interface.
As with the tree model, a JTable does not store its own data but obtains its data from a table model. JTable also has two other models: a column model and a list-selection model. The column model maintains the columns in the table while the list-selection model is used to access the rows, columns and cells in the table.
5.1 Creating JTables
Like the JTree, there are seven constructors for the JTable. Probably the simplest one is the constructor who accepts a two-dimensional array of objects as its parameter. Then the objects in the array will be displayed in a table.
For example
Object[][] cells = {
{ “Mercury”, 2440.0, 0, false, Color.yellow },
{“Venus”, 6052.0, 0, false, Color.yellow },
...
};
String[] columnNames = {“Planet”, “Radius”, “Moons”, “Gaseous”,
“Color”};
JTable table = new JTable(cells, columnNames);
As JTable doesn’t directly support scrolling when you have many rows, you need to create a JScrollPane to hold the table. If a table is not placed in a scroll pane, its column header will not be visible. To finish our job, put one more statement
JScrollPane pane = new JScrollPane(table);
The final program is here
import javax.swing.*;
import java.awt.*;
public class TestTable {
public static void main( String[] argv ) {
JFrame myframe = new JFrame("Test Table");
myframe.setSize(400, 300);
Object[][] cells = {
{ "Mercury", 2440.0, 0, false, Color.yellow },
{"Venus", 6052.0, 0, false, Color.yellow } };
String[] columnNames = {"Planet", "Radius", "Moons",
"Gaseous", "Color"};
JTable table = new JTable(cells, columnNames);
JScrollPane pane = new JScrollPane(table);
myframe.add(pane);
myframe.setLocationRelativeTo(null);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setVisible(true);
}
}
5.2 The Table Model
The TableModel is an interface. One of basic concrete classes implementing this interface is the DefaultTableModel class. With this class you can add, update and remove table data. To use this model, you can do it in this way
Object[][] cells = { .. .. .. };
String[] columnNames = { .. .. .. };
DefaultTableModel model = new DefaultTableMode(cells, columnNames);
JTable table = new JTable(model);
Then you use the model with table like
model.removeRow(1);
model.addColumn(“Distance”);
More methods please consult to the Java document.
5.3 The Table Column Models
The table column models manage columns in a table. For example you can use them to select, add, move and remove table columns.
The table column model of a table can be obtained by the getColumnModel() method of the table instance.
5.4 The ListSelectionModel
The ListSelectionModel should be obtained from the TableColumnModel by using its getSelectionModel() method.