Blakes 21 Days Chapter 10 Document
Day 10, Building a Swing Interface
- Top
- 285 Although computers can be operated in a command line environment such as a Linux shell or the Windows command prompt,
- most computer users expect software to feature a graphical user interface (GUI) and to receive input with a mouse and keyboard.
- 285 GUI software can be one of the more challenging tasks for a novice programmer, but as you learned yesterday, Java has simplified the process with Swing.
- 285 Swing offers the following features:
- Common user interface components,
- including buttons, text fields, text areas, labels, check boxes, radio buttons, scrollbars, lists, menu items, and sliders.
- Containers - interface components that can be used to hold other components (including other containers).
- Cintainers include frames, panels, menus, menu bars, and tabbed panes.
Swing Features
- Top
- 286 Most components and containers you learned about yesterday were Swing versions of classes that were part of the Abstract Windowing Toolkit,
- the original Java package for GUI programming.
- 286 Swing offers many additional new components, including mnemonics, ToolTips, and standard dialog boxes.
Standard Dialog Boxes
- Top
- 286 The JOptionPane class offers several methods you can use to create standard dialog boxes,
- small windows that ask a question, warn a user, or provide an important message.
- Figure 10.1 shows an example
Figure 10.1 "a standard dialog box" goes here !
- Top
- 286 You have doubtless seen dialog boxes like one shown in Figure 10.1
- When your system crashes, a dialog box appears to break the bad news.
- When you delete files, a dialog box pops uo to make sure that you really want to do so.
- 286 These windows are an effective way to communicate with a user without the overhead of creating a new class to represent the window,
- adding components to it, and writing event-handling methods to receive input.
- All these tasks are handled automatically when one of the standard dialog boxes offered by JOptionPane is used.
- Top
- 286 The four classes of the standard dialog boxes are as follows:
- ConfirmDialog - Asks a question, with buttons for Yes, No, and Cancel responses
- InputDialog - Prompts for text input
- MessageDialog - Displays a message
- OptionDialog - Comprises all three of the other dialog box types
- Each of these dialog boxes has its own display method in the JOptionPane class.
Confirm Dialog Boxes
- Top
- 287 The easiest way to create a Yes/No/Cancel dialog box is by calling the showConfirmDialog (Component, Object) method.
- The Component argument specifies the container that's the parent of the dialog box, which determines where the dialog window should be displayed.
- If null is used instead of a container, or if the container is not a JFrame object, the dialog box will be centered onscreen.
- 287 The second argument, Object, can be a string, a component, or an Icon object.
- If it's a string, that text will be displayed in the dialog box.
- If it's a component or an Icon, that object will be displayed in place of a text message.
- 287 This method returns one of five possible integer values,
- each a class constant of JOptionPane:
- YES_OPTION
- NO_OPTION
- CANCEL_OPTION
- OK_OPTION
- CLOSED_OPTION
- The following example uses a confirm dialog box with a text message and stores the response in the response variable:
int response = JOptionPane.showConfirmDialog(Null,
"Should I delete all of your irreplaceable personal files?");
- This dialog box was shown in Figure 10.1
- Top
- 287 Another method offers more options for the dialog box:
- showConfirmDialog (Component, Object, String, int, int)
- The first two arguments are the same as those in other showConfirmDialog() methods.
- The last three arguments are the following:
- A string that will be displayed in the dialog box's title bar.
- An integer that indicates which option buttons will be shown.
- It should be equal to one of the class constants YES_NO_CANCEL_OPTION or YES_NO_OPTION
- An integer that describes the kind of dialog box it is, using the class constants:
- ERROR_MESSAGE
- IMPORTANT_MESSAGE
- PLAIN_MESSAGE
- QUESTION_MESSAGE
- WARNING_MESSAGE
- (This argument is used to determine which icon to draw in the dialog box along with the message.)
- For example:
int response = JOptionPane.showConfirmDialog(null,
"Error reading file. Want to try again?"),
"File Input Error",
JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE);
- Figure 10.2 shows the resulting dialog box.
Figure 10.2 goes here
Input Dialog Boxes
- Top
- 288 An input dailog box asks a question and uses a text field to store the response.
- Figure 10.3 shows an example.
Figure 10.3 goes here
- Top
- 288 The easiest way to create an input dialog box is with a call to the showInputDialog(Component, Object) method.
- The arguments are the parent component and the string, component, or icon to display in the box.
- 288 The input dialog box method call returns a string that represents the user's response.
- The following statement creates the input dialog box shown in Figure 10.3:
String response = JOptionPane.showInputDialog(null,
"Enter your name:");
- You also can create an input dialog box with the showInputDialog (Component, Object, String, int) method.
- The first two arguments are the same as the shorter method call, and the last two are the following:
- The title to display in the dialog box title bar
- One of five class constants describing the type of dialog box:
- ERROR_MESSAGE
- INFORMATION_MESSAGE
- PLAIN_MESSAGE
- QUESTION_MESSAGE
- WARNING_MESSAGE
- Top
- 289 The following statement uses this method to create an input dialog box:
JOptionPane.showMessageDialog(null,
"An asteroid has destroyed the Earth"),
"Asteroid Destruction Alert",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);,
Option Dialog Boxes
- Top
- 290 The most complex of the dialog boxes is the option dialog box,
- which combines the features of all the other dialog boxes.
- It can be created with the showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object) method.
- 290 The arguments to this method are as follows:
- The parent component of the dialog box
- The text, icon, or component to display
- A string to display in the title bar
- The type of box, using the class constant YES_NO_OPTION or YES_NO_CACEL_OPTION, or the value 0 if other buttons will be used instead
- The icon to display, using the class constants:
- ERROR_MESSAGE
- INFORMATION_MESSAGE
- PLAIN_MESSAGE
- QUESTION_MESSAGE
- WARNING_MESSAGE
- or the value 0 if none of these should be used
- An Icon object to display instead of one of the icons in the proceding argument
- An array of objects holding the objects that represent the choices in the dialog box if YES_NO_OPTION and YES_NO_CANCEL_OPTION are not used
- The object representing the default selection if YES_NO_OPTION and YES_NO_CANCEL_OPTION are not used
- Top
- 290 The final two arguments offer a wide range of possibilities for the dialog box.
- You can create an array of strings that hold the text of each button to display on the dialog box.
- Top
- 290 The following example creates an option dialog box that uses an array of String objects for the options in the box and the gender[2] element as the default selection:
String[] gender = {
"Male",
"Female",
"None of Your Business"
};
int response = JOptionPane.showOptionDialog(null,
"What is your gender?",
"Gender",
0,
JOptionPane.INFORMATION_MESSAGE,
null,
gender,
gender[2]);
System.out.println("You chose " + gender[response]);
- Figure 10.5 shows the resulting dialog box.
Figure 10.5 goes here
Using Dialog Boxes
- Top
- 291 The next project shows a series of dialog boxes in a working program.
- The FeedInfo application in the com.java21days package uses dialog boxes to get information from the user:
- that information is then placed into the text fields in the application's main window.
- 291 Enter Listing 10.1 and save the result.
Listing 10.1 The Full Text of FeedInfo.java
- Top
- page 291 - 292
package com.java21days;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class FeedInfo extends JFrame {
private JLabel nameLabel = new JLabel("Name : ",
SwingConstants.RIGHT);
private JTextField name;
private JLabel urlLabel = new JLabel("URL: ",
SwingConstants.RIGHT);
private JTextField url;
private JLabel typeLabel = new JLabel("Type: ",
SwingConstants.RIGHT);
private JTextField type;
public FeedInfo() {
super("Feed Information");
setSize(400, 145);
setDefaultCloseOperation(JFRame.EXIT_ON_CLOSE);
setLookAndFeel();
// Site name
String response1 = JOptionPane.showInputDialog(null,
"Enter the site name:");
name = new JTextField(response1, 20);
// Site address
String response2 = JOptionPane.showInputDialog(null,
"Enter the site address:");
url = new JTextField(response2, 20);
// Site type
String[] choices = { "Personal", "Commercial", "Unknown" };
int response3 = JOptionPane.showOptionDialog(null,
"What type of site is it?",
"Site Type",
0,
JOptionPane.QUESTION_MESSAGE,
null,
choices,
choices[0]);
type = new JTextField(choices[response3], 20);
setLayout(new GridLayout(3, 2));
add(nameLabel);
add(name);
add(urlLabel);
add(url);
add(typeLabel);
add(type);
setLookAndFeel();
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
System.err.println("Couldn't use the system "
+ "look and feel: " + e);
}
}
public static void main(String[] arguments) {
FeedInfo frame = new FeedInfo();
}
}
An Explanation
- Top
- 292 After you fill in the fields in each dialog box, you see the application's main window,
- which is displayed in Figure 10.6
- Three text fields have values supplied by dialog boxes.
Figure 10.6 goes here
- Top
- 293 Much of this application is boilerplate code that can be used with any Swing application.
- The following lines relate to the dialog boxes:
- In lines 24 - 26, an input dialog box asks the user to enter a site name.
- This name is used in the constructor for a JTextField object, placing it in the text field.
- In lines 29 - 31, a similar input dialog box asks for a site address,
- which is used in the constructor for another JTextField object.
- In line 34, an array of String objects called choices is created,
- and three elements are given values
- In lines 35 - 42, an option dialog box asks for the site type.
- The choices array is the seventh argument,
- which sets up three buttons on the dialog box labeled with the strings in the array:
- "Personal", "Commercial", and "Unknown".
- The last argument, choices[0], designates the first array element as the default selection in the dialog box.
- Line 43 contains the response to the option dialog box,
- an integer identifying the array element that was selected.
- It is stored in a JTextField component called type.
- Top
- 293 The look and feel, which is established in the setLookAndFeel() method in lines 56 - 66,
- is called at the begining and end of the frame's constructor method.
- Because you're opening several dialog boxes in the constructor, you must set up the look and feel before opening them.
- 293 This class designates a look and feel differently than previous examples today and on Day 9, "Working with Swing."
- The setLookAndFeel() method is called within the constructor in line 22.
- To ensure that all components in the user interface reflect the look and feel,
- the SwingUtilities class method SwingUtilities.updateComponentTreeUI(Component) is called with this as the argument,
- which refers to the FeedInfo object being created.
Sliders
- Top
- 294 Sliders, which are implemented in Swing with the JSlider class, enable the user to set a number by sliding a control within the range of a minimum and maximum value.
- In many cases, a slider can be used for numeric input instead of a text field.
- This has the advantage of restricting input to a range of acceptable values.
- 294 Figure 10.7 shows a JSlider component.
Figure 10.7 goes here
- Top
- 294 Sliders are horizontal by default.
- You can explicitly set the orientation using two class constants of the SwingConstants interface: HORIZONTAL or VERTICLE.
- 294 You can use the following constructor methods:
- JSlider(int) - A slider with the specified orientation, a minimum value of 0, maximum value of 100, and starting value of 50.
- JSlider(int, int) - A slider with the specified minimum value and maximum value
- JSlider(int, int, int) - A slider with the specified minimum value, maximum value, and starting value
- JSlider(int, int, int, int) - A slider with the specified orientation, minimum value, maximum value, and starting value
- Top
- 294 Slider components have an optional label that can be used to indicate the minimum value, maximum value, and two different sets of tick marks ranging between the values.
- The default values are a minimum of 0, maximum of 100, starting value of 50, and horizontal orientation.
- Top
- 294 The elements of this label are established by calling several methods of the JSlider:
- setMajorTickSpacing(int) - Separates major tick marks by the specified distance.
- The distance is nit in pixels, but in values between the minimum and maximum values represented by the slider.
- setMinorTickSpacing(int) - Separates minor tick marks by the specified distance.
- Minor ticks are displayed as half the height of major ticks.
- setPaintTicks(boolean) - Determines whether the tick marks should be displayed (true) or not (false).
- setPaintLabels(boolean) - Determines whether the slider's numeric label should be displayed (true) or not (false).
- 294 These methods should be called on the slider before it is added to a container.
Second Program
- Top
- 295 Listing 10.2 contains the Slider.java source code, the application was shown in Figure 10.7
Listing 10.2 The Full Text of Slider.java
- Top
- page 295
package com.java21days;
import javax.swing.*;
public class Slider extends JFrame {
public Slider() {
super("Slider");
setDefaultCloseOperation(JFRame.EXIT_ON_CLOSE);
setLookAndFeel();
JSlider pick = new JSlider(JSlider.HORIZONTAL, 0, 30, 5);
pick.setMajorTickSacing(10);
pick.setMinorTickSacing(1);
pick.setPaintTicks(true);
pick.setPaintLabels(true);
add(pick);
pack();
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
System.err.println("Couldn't use the system "
+ "look and feel: " + e);
}
}
public static void main(String[] arguments) {
Slider frame = new Slider();
}
}
Explanation
- Top
- 296 Lines 12 - 16 contain the code that's used to create a JSlider component, set up its tick marks to be displayed, and add the component to a container.
- The rest of the program is a basic framework for an application that consists of a main JFrame container with no menus.
Scroll Panes
- Top
- 296 In early versions of Java, text areas and some other components had a built-in scrollbar.
- The bar could be used when the text in the component took up more space than the component could display.
- Scrollbars could be used in either the vertical or horizontal direction to scroll through the text.
- 296 One of the most common examples of scrolling is in a web browser, where a scrollbar can be used on any page bigger than the bowser's display area.
- 296 Swing changes the rules for scrollbars to the following:
- For a component to be able to scroll, it must be added to a JScrollPane container.
- This JScrollPane container is added to a container in place of the scrollable component.
- Top
- 296 Scroll panes can be created using the JScrollPane(Object) constructor, where Object represents the component that can be scrolled.
- 296 The following example creates a text area in a Scroll pane called scroller and then adds it to a container called mainFrame:
JTextArea textBox = new JTextArea(7, 30);
JScrollPane scroller = new JScrollPane(textBox);
mainFrame.add(scroller);
- As you work with a Scroll pane, it often can be useful to indicate the size you want it to occupy on the interface.
- You do so by calling the setPrefferredSize(Dimension) method of the Scroll pane before adding it to the container.
- The Dimension object represents the width and height of the preffered size in pixels
- The following code builds on the previous example by setting the preffered size of scroller:
Dimension pref = new Dimension(350, 100);
scroller.setPrefferedSize(pref);
- You should set the dimensions before scroller is added to a container.
- Top
- 297 CAUTION: This is one of many situations in Swing where you must do something in the proper order for it to work correctly.
- For most components, the order is the following:
- Create the component,
- set up the component fully,
- and add the component to a container.
- Top
- 297 By default, a Scroll pane does not display scrollbars unless they are needed.
- If the component inside the pane is no larger than the pane itself, the bars won't appear.
- In the case of components such as text areas, where the component size might increase as the program is used,
- the bars automatically appear when they're needed and disappear when they're not.
- 297 To override this behavior, you can set a policy for a JScrollBar component when you create it, using one of several constants in the ScrollPaneConstants interface:
- HORIZONTAL_SCROLLBAR_ALWAYS
- HORIZONTAL_SCROLLBAR_AS_NEEDED
- HORIZONTAL_SCROLLBAR_NEVER
- VERTICAL_SCROLLBAR_ALWAYS
- VERTICAL_SCROLLBAR_AS_NEEDED
- VERTICAL_SCROLLBAR_NEVER
- These class constants are used with the JScrollPane(Object, int, int) constructor,
- which specifies the component in the pane, the vertical scrollbar policy, and the horizontal scrollbar policy.
- Here's an example:
JScrollPane scroller = new JScrollPane(textBox,
VERTICAL_SCROLLBAR_ALWAYS,
HORIZONTAL_SCROLLBAR_NEVER);
Toolbars
- Top
- 297 A toolbar, created in Swing with the JToolBar class, is a container that groups several components into a row or column.
- These components are most often buttons.
- 297 Toolbars are rows or columns of components that group the most commonly used program options.
- Toolbars often contain buttons and lists and can be used as an alternative to using pull-down menus or shortcut keys.
- 297 Toolbars are horizontal by default, but the orientation can be set explicitly with the HORIZONTAL or VERTICAL class variables of the SwingContants interface.
- Top
- 298 Constructor methods include the following:
- JToolBar() - Creates a new toolbar
- JToolBar(int) - Creates a new toolbar with the specified orientation.
- 298 After you have created a toolbar, you can add components to it with the toolbar's add(Object) method, where Object represents the component to place on the toolbar.
- 298 Many programs that use toolbars enable the user to move the bars.
- These are called dockable toolbars because you can dock them along an edge of the screen, similar to docking a boat.
- Swing toolbars also can be docked into a new window, separate from the original.
- Top
- 298 For best results, a dockable JToolBar component should be arranged in a container using the BorderLayout class,
- which is a user interface class called a layout manager.
- A border layout divides a container into five areas: north, south, east, west, and center.
- Each of the directional components takes up whatever space it needs, and the rest are allocated to the center
- Top
- 298 The toolbar should be placed in one of the directional areas of the border layout.
- The only other area of the layout that can be filled is the center.
- (You learn about layout managers such as border layout during tomorrow's lesson, Day 11, "Arranging Components on a User Interface")
Third Program
- Top
- 298 Figure 10.8 shows a dockable toolbar occupying the south area of a border layout.
- A text area has been placed in the center.
Figure 10.8 A dockable toolbar and a text area - goes here!
- Top
- 298 Listing 10.3 shows the source code used to produce this application.
LISTING 10.3 The Full Text of FeedBar.java
- Top
- page 299-300
package com.java21days;
import java.awt.*;
import javax.swing.*;
public class FeedBar extends JFrame {
public FeedBar() {
super("FeedBar");
setDefaultCloseOperation(JFRame.EXIT_ON_CLOSE);
setLookAndFeel();
// create icons
ImageIcon loadIcon = new ImageIcon("load.gif");
ImageIcon saveIcon = new ImageIcon("save.gif");
ImageIcon subIcon = new ImageIcon("subscribe.gif");
ImageIcon unsubIcon = new ImageIcon("unsubscribe.gif");
// create buttons
JButton load = new JButton("Load", loadIcon);
JButton load = new JButton("Save", saveIcon);
JButton sub = new JButton("Subscribe", subIcon);
JButton unsub = new JButton("Unsubscribe", unsubIcon);
// add buttons to toolbar
bar.add(load);
bar.add(save);
bar.add(sub);
bar.add(unsub);
// prepare user interface
JTextArea edit = new JTextArea(8, 40);
JScrollPane scroll = new JScrollPane(edit);
BorderLayout bord = new BorderLayout();
setLayout(bord);
add("North", scroll);
add("Center", scroll);
pack();
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
System.err.println("Couldn't use the system "
+ "look and feel: " + e);
}
}
public static void main(String[] arguments) {
FeedBar frame = new FeedBar();
}
}
The Explanation
- Top
- 300 This application uses four images to represent the graphics on the buttons,
- the same graphics used in the IconFrame project yesterday.
- If you haven't downloaded them yet, they are available on the book's official website at www.java21days.com on the Day 10 page.
- You also can use graphics from your own computer.
- 300 Four ImageIcon objects are created from the four graphics in lines 13 - 16, and then they are used to create buttons in lines 18 - 21.
- A JToolBar is in line 23, and the buttons are added to it in lines 24 - 27.
- 300 The toolbar in this application starts at the top edge of the frame, but it can be moved.
- The component can be grabbed by its handle,
- the area immediately to the left of the Load button shown in Figure 10.8
- If you drag it within the window, you can dock it along different edges of the application window.
- When you release the toolbar, the application is rearranged using the border layout manager.
- You also can drag the toolbar outside the application window.
- 300 If the toolbar has been dragged to its own window, when the frame is closed, the toolbar also will close.
- 300 Although toolbars are most commonly used with graphical buttons, they can contain textual buttons, combo boxes, and other components.
Progress Bars
- Top
- 300 Progress bars are components used to show how much time is left before a task is complete.
- 300 Progress bars are implemented in Swing through the JProgressBar class.
- Figure 10.9 shows a Java application that uses this component.
Figure 10.9 A progress bar in a frame, goes here!
- Top
- 300 Progress bars are used to track the progress of a task that can be represented numerically.
- They are created by specifying a minimum and a maximum value that represents the points at which the task is beginning and ending.
- 301 Consider a software program that consists of 335 files when it is installed on a computer.
- This is a good example of a task that can be numerically quantified.
- The number of files transferred can be used to monitor the progress of the task.
- The minimum value is 0, and the maximum value is 335.
- Top
- 301 Constructor methods include the following:
- JProgressBar() - Creates a new progress bar
- JProgressBar(int, int) - Creates a new progress bar with the specified minimum value and maximum value
- JProgressBar(int, int, int) - Creates a new progress bar with the specified orientation, minimum value and maximum value
- Top
- 301 The orientation of a progress bar can be established with the SwingConstants.VERTICAL and SwingConstants.HORIZONTAL class constants.
- Progress bars are horizontal by default.
- 301 You also can set the minimum and maximum values by calling the progress bar's setMinimum(int) and setXaximum(int) values with the indicated values.
- Top
- 301 To update a progress bar, you call its setValue(int) method with a value indicating how far along the task is at the moment.
- This value should be somewhere between the minimum and maximum values established for the bar.
- The following example tells the install progress bar in the previous example of a software installation how many files have been uploaded thus far:
int filesDone = getNumberOfFiles();
install.setValue(filesDone);
- In this example, the getNumberOfFiles() method represents some code that would be used
- to keep track of how many files have been copied, so far, during the installation.
- When this value is passed to the progress bar by the setValue() method,
- the bar is immediately updated to represent the percentage of the task that has been completed.
- Top
- 301 Progress bars often include a text label in addition to the graphic of an empty box filling up.
- This label displays the percentage of the task that has been completed.
- You can set it up for a bar by calling the setStringPainted(boolean) method with a value of true.
- A false argument turns off this label.
Fourth Program
- Top | Back to Day 16: Page 458, Listing 16.2, ProgressMonitor2.java
- 301 Listing 10.4 contains ProgressMonitor, the application shown at the beginning of this section in Figure 10.9
LISTING 10.4 The Full Text of ProgressMonitor.java
- Top
- page 302-303
package com.java21days;
import java.awt.*;
import javax.swing.*;
public class ProgressMonitor extends JFrame {
JProgressBar current;
JTextArea out;
JButton find;
int num = 0;
public ProgressMonitor() {
super("Progress Monitor");
setDefaultCloseOperation(JFRame.EXIT_ON_CLOSE);
setLookAndFeel();
setSize(205, 68);
setLayout(new FlowLayout());
current = new JProgressBar(0, 2000);
current.setValue(0);
current.setStringPainted(true);
add(current);
}
public void iterate() {
while (num < 2000) {
current.setValue(num);
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
num += 95;
}
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
System.err.println("Couldn't use the system "
+ "look and feel: " + e);
}
}
public static void main(String[] arguments) {
ProgressMonitor frame = new ProgressMonitor();
frame.setVisible(true);
frame.iterate();
}
}
The Explanation
- Top
- 303 The ProgressMonitor application uses a progress bar to track the value of the num variable.
- The progress bar is created in lines 25 - 33 loops while num is less than 2,000 and increases num by 95 each iteration.
- The progress bar's setValue() method is called in line 27 of the loop with num as an argument, causing the bar to use that value when charting progress.
- 303 Using a progress bar is a way to make a program more user-friendly when it will be busy for more than a few seconds.
- Software users like progress bars because they estimate how much more time something will take.
- 303 Progress bars also provide another essential piece of information, proof that the program is still running and has not crashed.
Menus
- Top
- 303 One way you can enhance a frame's usability is to give it a menu bar, a series of pull-down menus used to perform tasks.
- Menus often duplicate the same tasks you could accomplish by using buttons and other user interface components, giving users two ways to get work done.
- 303 Menues in Java are supported by three components that work in conjunction with each other:
- JMenuItem - An item on a menu
- JMenu - A drop-down menu that contains one or more JMenuItem components, other interface components, and separators, lines displayed between items
- JMenuBar - A container that holds one or more JMenu components and displays their names
- 303 A JMenuItem component is like a button and can be set up using the same constructor methods as a JButton component.
- Call it with JMenuItem(String) for a text item, JMenuItem(Icon) for an item that displays a graphics file, or JMenuItem(String, Icon) for both.
- Top
- 304 The following statements create seven menu items:
JMenuItem j1 = new JMenuItem("Open");
JMenuItem j2 = new JMenuItem("Save");
JMenuItem j3 = new JMenuItem("Save as Template");
JMenuItem j4 = new JMenuItem("Page Setup");
JMenuItem j5 = new JMenuItem("Print");
JMenuItem j6 = new JMenuItem("Use as Default Message Style");
JMenuItem j7 = new JMenuItem("Close");
- 304 A JMenu container holds all the menu items for a drop-down menu.
- To create it, call the JMenu(String) constructor with the name of the menu as an argument.
- This name appears on the menu bar.
- 304 After you have created a JMenu container, call its add(JMenuItem) to add a menu item to it.
- New items are placed at the end of the menu.
- 304 The item you put on a menu doesn't have to be a menu item.
- Call the add(Component) method with a user interface component as the argument.
- One that often appears on a menu is a check box (the JCheckBox class in Java).
- Top
- 304 To add a line separator to the end of the menu, call the addSeparator() method.
- Separators often are used to visually group several related items on a menu.
- 304 You can also add text to a menu that serves as a label of some kind.
- Call the add(String) method with the text as the argument.
- 304 Using the seven menu items from the preceding example, the following statements create a menu and fill it with all those items and three separators:
JMenu m1 = new JMenu("File");
m1.add(j1);
m1.add(j2);
m1.add(j3);
m1.addSeparator();
m1.add(j4);
m1.add(j5);
m1.addSeparator();
m1.add(j6);
m1.addSeparator();
m1.add(j7);
- Top
- 304 A JMenuBar container holds one or more JMenu containers and displays each of their names.
- The most common place to see a menu bar is directly below an application's title bar.
- 305 To create a menu bar, call the JMenuBar() constructor method with no arguments.
- Add menus to the end of a bar by calling its add(JMenu) method.
- 305 After you have created all your items, added them to menus, and added the menus to a bar, you're ready to add them to a frame.
- Call the frame's setJMenuBar(JMenuBar) method.
- 305 The following statement finishes the current example by creating a menu bar, adding a menu to it, and then placing the bar on a frame called gui:
JMenuBar bar = new JMenuBar();
bar.add(m7);
gui.setJMenuBar(bar);
- Figure 10.10 shows what this menu looks like on an otherwise empty menu bar.
Figure 10.10 - A frame with a menu bar - goes here
- Top
- 305 Although you can open and close a menu and select items, nothing happens in response.
- You'll learn how to receive user input for this component and others during Day 12, "Responding to User Input."
Fifth Program
- Top
- 305 Listing 10.5 is an expanded version of the FeedBar project, adding a menu bar that holds one menu and four individual items.
LISTING 10.5 The Full Text of FeedBar2.java
- Top
- page 305-307
package com.java21days;
import java.awt.*;
import javax.swing.*;
public class FeedBar2 extends JFrame {
public FeedBar2() {
super("FeedBar 2");
setDefaultCloseOperation(JFRame.EXIT_ON_CLOSE);
setLookAndFeel();
// create icons
ImageIcon loadIcon = new ImageIcon("load.gif");
ImageIcon saveIcon = new ImageIcon("save.gif");
ImageIcon subIcon = new ImageIcon("subscribe.gif");
ImageIcon unsubIcon = new ImageIcon("unsubscribe.gif");
// create buttons
JButton load = new JButton("Load", loadIcon);
JButton load = new JButton("Save", saveIcon);
JButton sub = new JButton("Subscribe", subIcon);
JButton unsub = new JButton("Unsubscribe", unsubIcon);
// add buttons to toolbar
bar.add(load);
bar.add(save);
bar.add(sub);
bar.add(unsub);
// create menu
JMenuItem j1 = new JMenuItem("Load");
JMenuItem j2 = new JMenuItem("Save");
JMenuItem j3 = new JMenuItem("Subscribe");
JMenuItem j4 = new JMenuItem("Unsubscribe");
JMenu menubar = new JMenu("Feeds");
menu.add(j1);
menu.add(j2);
menu.addSeparator();
menu.add(j3);
menu.add(j4);
menubar.add(menu);
// prepare user interface
JTextArea edit = new JTextArea(8, 40);
JScrollPane scroll = new JScrollPane(edit);
BorderLayout bord = new BorderLayout();
setLayout(bord);
add("North", scroll);
add("Center", scroll);
setJMenuBar(menubar);
pack();
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
System.err.println("Couldn't use the system "
+ "look and feel: " + e);
}
}
public static void main(String[] arguments) {
FeedBar2 frame = new FeedBar2();
}
}
The Explanation
- Top
- 307 This application creates the menu bar in Lines 29 - 40 and adds it to the frame in line 48.
- Figure 10.10 shows the application running.
- Figure 10.10 is on page 305
Tabbed Panes
- Top
- 307 Tabbed panes, a group of stacked panels in which only one panel can be viewed at a time, are implemented in Swing by the JTabbedPane class.
- 307 To view a panel, you click the tab that contains its name.
- Tabs can be arranged horizontally across the top or bottom of the component or vertically along the left or right side.
- 307 Tabbed panes are created with the following three constructor methods:
- JTabbedPane() - Creates a vertical tabbed pane along the top that does not scroll
- JTabbedPane(int) - Creates a tabbed pane that does not scroll and has the specified placement
- JTabbedPane(int, int) - Creates a tabbed pane with the specified placement (first argument) and scrolling policy (second argument)
- Top
- 307 The placement of a tabbed pane is the position where its tabs are displayed in relation to the panels.
- Use one of four class variables as the argument to the constructor:
- JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT, JTabbedPane.RIGHT.
- 307 The scrolling policy determines how tabs will be displayed when there are more tabs than the interface can hold.
- A tabbed pane that does not scroll displays extra tabs on their own line, which can be set up using the JTabbedPane.WRAP_TAB_LAYOUT class variable.
- A tabbed pane that scrolls displays scrolling arrows besides the tabs.
- This can be set up with JTabbedPane.SCROLL_TAB_LAYOUT.
- 307 After you create a tabbed pane, you can add components to it by calling the pane's addTab(String, Component) method.
- The String argument will be used as the tab's label.
- The second argument is the component that will make up one of the tabs on the pane.
- It's common but not required to use a JPanel object for this purpose.
Sixth Program
- Top
- 308 The TabPanels application in Listing 10.6 displays a pane with five tabs, each holding its own panel.
LISTING 10.5 The Full Text of TabPanels.java
- Top
- page 308
package com.java21days;
import java.awt.*;
import javax.swing.*;
public class TabPanels extends JFrame {
public TabPanels() {
super("Tabbed Panes");
setDefaultCloseOperation(JFRame.EXIT_ON_CLOSE);
setLookAndFeel();
setSize(480, 218);
JPanel mainSettings = new JPanel();
JPanel advancedSettings = new JPanel();
JPanel privacySettings = new JPanel();
JPanel emailSettings = new JPanel();
JPanel securitySettings = new JPanel();
JTabbedPane tabs = new JTabbedPane();
tabs.addTab("Main", mainSettings);
tabs.addTab("Advanced", advancedSettings);
tabs.addTab("Privacy", privacySettings);
tabs.addTab("E-Mail", emailSettings);
tabs.addTab("Security", securitySettings);
add(tabs);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
SwingUtilities.updateComponentTreeUI(this);
} catch(Exception e) {
System.err.println("Couldn't use the system "
+ "look and feel: " + e);
}
}
public static void main(String[] arguments) {
TabPanels frame = new TabPanels();
}
}
The Explanation
- Top
- 309 Five panels are created in lines 13 - 17.
- A tabbed pane is created, and then the panels are added to each tab in lines 18 - 23.
- Each panel can hold its own user interface components.
- 309 Figure 10.11 shows the application running.
Figure 10.11 - A tabbed pane with five tabs - goes here
- Top
- 309 NOTE: The TOP, BOTTOM, LEFT, and RIGHT contants used in JTabbedPane constructors
- are part of the SwingConstants interface in the javax.swing package.
- The interface contains a set of integer constants that help position and align components.
Summary
- Top
- 309 You now know how to paint a user interface onto a Java application window using the components of the Swing package
- Object-oriented programming is beneficial because of its benefits: improved reliability, reusability, and maintenance.
- 309 Swing includes classes for many of the buttons, bars, lists, and fields you would expect to see on a program.
- It also includes more advanced components such as sliders, dialog boxes, progress bars, and menu bars.
- You implement interface components by creating an instance of their class and adding it to a container such as a frame.
- You use the container's add() method or a similar method specific to the container, such as the tabbed pane's addTab() method.
- 309 Today, you developed components and added them to an interface.
- During the next two days, you will learn about two tasks required to make a graphical interface usable.
- You will see how to arrange components to form a whole interface and how to recieve input from a user through these components.
- 309 Swing offers a lot more user interface components than the ones covered today and yesterday.
Q & A
- Top
- 310 Q Can an application be created without Swing ?
- 310 A Certainly. Swing is just an expansion on the Abstract Windowing Toolkit, so you could use only AWT classes to design your interface and receive input from a user.
- But there's no comparison between Swing's capabilities and those offered by the AWT.
- With Swing, you can use many more components, control them in more sophisticated ways, and count on better performance and more reliability
- Java includes an alternative to Swing called JavaFX that had the original design goal of replacing it in a future release of the language,
- JavaFX is designed for the creation of desktop applications, mobile applications, and Rich Internet Applications (RIA).
- JavaFX includes its own user interface components and support for animation, 3D graphicsand HTML 5.
- The popularity of Android for Java mobile development has undercut some of the rationale for JavaFX, so it appears Swing will continue to be the most widely implemented GUI platform in Java.
- Other user interface libraries also extend or compete with Swing.
- One of the most popular is the Standard Widget Toolkit (SWT), an open source GUI library vreated by the Eclipse project.
- The SWT offers components that appear and behave like the interface components offered by each operating system.
- For more information, visit www.eclipse.org/swt
- Q In the Slider application, what does the pack() statement do ?
- A Every interface component has a preferred size, although this often is disregarded by the layout manager used to arrange the component within a container.
- Calling a frame or window's pack() method causes it to be resized to fit the preferred size of the components it contains.
- Because the Slider application does not set a size for the frame, calling pack() sets it to an adequate size before the frame is displayed.
- Q When I try to create a tabbed pane, all that appears are the tabs - the panels themselves are not visible. What can I do to correct this ?
- A Tabbed panes won't work correctly until their components have been fully set up with components inside them.
- If a tab's panes are empty, nothing appears below or besides the tabs.
- Make sure that the panels you are putting into tabs display all their components.
Quiz - Questions
- Top | Review today's material by taking this three-question quiz.
- Which user interface component is common in software installation programs ?
- Sliders
- Progress bars
- Dialog boxes
- Which Java package includes a class for clickable buttons ?
- java.awt (Abstract Windowing Toolkit)
- javax.swing (Swing)
- Both
- Which user interface component can be picked up and moved around ?
- JSlider.
- JToolbar
- Both
Answers
- Top | Note A is 1, B is 2, and C is 3
- B. Progress bars are useful when used to display the progress of a file-copying or file-extracting activity.
- C. Swing duplicates all the simple user interface components included in the Abstract Windowing Toolkit.
- B. The toolbar can be dragged to the top, right, left, or bottom of the interface and also out of the interface.
Certification Practice
- Top
- 311 The following question is the kind of thing you could expect to be asked on a Java programming certification test. Answer it without looking at today's material or using the Java compiler to test the code.
- The answer is available on the book's website at www.java21days.com | 21 Days Grid | 10's Page | 10's Certification Answers Page
- Given:
import java.awt.*;
import javax.swing.*
public class AskFrame extends JFrame {
public AskFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSlider value = new JSlider(0, 255, 100);
add(value);
setSize(450, 150);
setVisible(true);
super();
}
public static void main(Sting[] arguments) {
AskFrame af = new AskFrame();
}
}
- What will happen when you compile and run this source code ?
- It compiles without error and runs correctly.
- It compiles without error but does not display anything in the frame.
- It does not compile because of the super() statement.
- It does not compile because of the add() statement.
Exercise
- Top
- To extend your knowledge of the subjects covered today, try the following exercises:
- Create an input dialog box that can be used to set the title of the frame that loaded the dialog box.
- Create a modified version of the ProgressMonitor application that also displays the value of the num variable in a text field.