So far, all our user interface components have appeared inside a frame window that was created in the application. This is the most common situation if you write applets that run inside a web browser. But if you write applications, you usually want separate dialog boxes to pop up to give information to or get information from the user.
Just as with most windowing systems, AWT distinguishes between modal and modeless dialog boxes. A modal dialog box won’t let users interact with the remaining windows of the application until he or she deals with it. You use a modal dialog box when you need information from the user before you can proceed with execution. For example, when the user wants to read a file, a modal file dialog box is the one to pop up. The user must specify a file name before the program can begin the read operation. Only when the user closes the (modal) dialog box can the application proceed.
A modeless dialog box lets the user enter information in both the dialog box and the remainder of the application. One example of a modeless dialog is a toolbar. The toolbar can stay in place as long as needed, and the user can interact with both the application window and the toolbar as needed.
We start this section with the simplest dialogs—modal dialogs with just a single message. Swing has a convenient JOptionPane class that lets you put up a simple dialog without writing any special dialog box code. Next, you see how to write more complex dialogs by implementing your own dialog windows. Finally, you see how to transfer data from your application into a dialog and back. We conclude this section by looking at two standard dialogs: file dialogs and color dialogs.
File dialogs are complex, and you definitely want to be familiar with the Swing JFileChooser for this purpose—it would be a real challenge to write your own. The JColorChooser dialog is useful when you want users to pick colors.
Swing has a set of ready-made simple dialogs that suffice when you need to ask the user for a single piece of information. The JOptionPane has four static methods to show these simple dialogs:
Figure below shows a typical dialog. As you can see, the dialog has the following components:
An option dialog
The input dialog has an additional component for user input. This can be a text field into which the user can type an arbitrary string, or a combo box from which the user can select one item.
The exact layout of these dialogs, and the choice of icons for standard message types, depend on the pluggable look and feel.
The icon on the left side depends on one of five message types:
The PLAIN_MESSAGE type has no icon. Each dialog type also has a method that lets you supply your own icon instead. For each dialog type, you can specify a message. This message can be a string, an icon, a user interface component, or any other object. Here is how the message object is displayed:
You can see these options by running the program in Listing below Of course, supplying a message string is by far the most common case. Supplying a Component gives you ultimate flexibility because you can make the paint Component method draw anything you want.
The buttons on the bottom depend on the dialog type and the option type. When calling showMessageDialog and show Input Dialog, you get only a standard set of buttons (OK and OK/ Cancel, respectively). When calling showConfirmDialog, you can choose among four option types:
With the showOptionDialog you can specify an arbitrary set of options. You supply an array of objects for the options. Each array element is rendered as follows:
Any other object Apply toString and make a button with the resulting string as label The return values of these functions are as follows:
The showConfirmDialog and showOptionDialog return integers to indicate which button the user chose. For the option dialog, this is simply the index of the chosen option or the value CLOSED_OPTION if the user closed the dialog instead of choosing an option. For the confirmation dialog, the return value can be one of the following:
This all sounds like a bewildering set of choices, but in practice it is simple. Follow these steps:
For example, suppose you want to show the dialog in Figure below. The dialog shows a message and asks the user to confirm or cancel. Thus, it is a confirmation dialog. The icon is a question icon. The message is a string. The option type is OK _CANCEL _OPTION. Here is the call you would make:
The OptionDialogTest program
static int showConfirmDialog(Component parent, Object message, String title, int optionType)
shows a confirmation dialog or an internal confirmation dialog. (An internal dialog is rendered entirely within its owner frame.) Returns the option selected by the user (one of OK _OPTION, CANCEL _OPTION, YES _OPTION, NO _OPTION), or CLOSED_OPTION if the user closed the dialog.
int optionType, int messageType, Icon icon, Object options, Object default) shows an option dialog or an internal option dialog. (An internal dialog is rendered entirely within its owner frame.) Returns the index of the option selected by the user, or CLOSED_OPTION if the user canceled the dialog.
icon An icon to show instead of one of the standard icons options An array of options (can be strings, icons, or components) default The default option to present to the user
static Object show Input Dialog (Component parent, Object message, String title, int message- Type, Icon icon, Object values, Object default)
int messageType, Icon icon, Object values, Object default)
In the last section, you saw how to use the JOptionPane class to show a simple dialog. In this section, you see how to create such a dialog by hand.
a typical modal dialog box, a program information box that is displayed when the user clicks the About button.
To implement a dialog box, you extend the JDialog class. This is essentially the same process as extending JFrame for the main window for an application. More precisely:
When you call the superclass constructor, you will need to supply the owner frame, the title of the dialog, and the modality.
The owner frame controls where the dialog is displayed. You can supply null as the owner; then, the dialog is owned by a hidden frame.
The modality specifies which other windows of your application are blocked while the dialog is displayed. A modeless dialog does not block other windows. A modal dialog blocks all other windows of the application (except children of the dialog). You would use a modeless dialog for a toolbox that the user can always access. On the other hand, you would use a modal dialog if you want to force the user to supply required information before continuing.
An About dialog box
Here’s the code for a dialog box:
As you can see, the constructor adds user interface elements: in this case, labels and a button. It adds a handler to the button and sets the size of the dialog. To display the dialog box, you create a new dialog object and make it visible:
Actually, in the sample code below, we create the dialog box only once, and we can reuse it whenever the user clicks the About button.
When the user clicks the Ok button, the dialog box should close. This is handled in the event handler of the Ok button:
When the user closes the dialog by clicking on the Close box, then the dialog is also hidden. Just as with a JFrame, you can override this behavior with the setDefaultCloseOperation method.
The most common reason to put up a dialog box is to get information from the user. You have already seen how easy it is to make a dialog box object: Give it initial data and then call setVisible(true) to display the dialog box on the screen. Now let us see how to transfer data in and out of a dialog box.
Consider the dialog box that could be used to obtain a user name and a password to connect to some on-line service.
Password dialog box
Your dialog box should provide methods to set default data. For example, the Password- Chooser class of the example program has a method, setUser, to place default values into the next fields:
Once you set the defaults (if desired), you show the dialog by calling setVisible(true). The dialog is now displayed. The user then fills in the information and clicks the Ok or Cancel button. The event handlers for both buttons call setVisible(false), which terminates the call to setVisible(true). Alternatively, the user may close the dialog. If you did not install a window listener for the dialog, then the default window closing operation applies: The dialog becomes invisible, which also terminates the call to setVisible(true).
The important issue is that the call to setVisible(true) blocks until the user has dismissed the dialog. This makes it easy to implement modal dialogs You want to know whether the user has accepted or canceled the dialog. Our samplecode sets the ok flag to false before showing the dialog. Only the event handler for theOk button sets the ok flag to true. In that case, you can retrieve the user input from thedialog.
The example program contains another useful improvement. When you construct a JDialog object, you need to specify the owner frame. However, quite often you want to show the same dialog with different owner frames. It is better to pick the owner frame when you are ready to show the dialog, not when you construct the PasswordChooser object. The trick is to have the PasswordChooser extend JPanel instead of JDialog. Build a JDialog object on the fly in the showDialog method:
Note that it is safe to have owner equal to null. You can do even better. Sometimes, the owner frame isn’t readily available. It is easy enough to compute it from any parent component, like this:
We use this enhancement in our sample program. The JOptionPane class also uses this mechanism. Many dialogs have a default button, which is automatically selected if the user presses a trigger key ( ENTER in most “look and feel” implementations). The default button is specially marked, often with a thick outline.You set the default button in the root pane of the dialog: dialog.getRootPane().setDefaultButton(okButton
If you follow our suggestion of laying out the dialog in a panel, then you must be careful to set the default button only after you wrapped the panel into a dialog. The panel itself has no root pane.
When you write an application, you often want to be able to open and save files. A good file dialog box that shows files and directories and lets the user navigate the file system is hard to write, and you defnitely don’t want to reinvent that wheel. Fortunately, Swing provides a JFileChooser class that allows you to display a file dialog box similar to the one that most native applications use. JFileChooser dialogs are always modal. Note that the JFileChooser class is not a subclass of JDialog. Instead of calling set- Visible(true), you call showOpenDialog to display a dialog for opening a file or you call show Save Dialog to display a dialog for saving a file. The button for accepting a file is then automatically labeled Open or Save. You can also supply your own button label with the showDialog method. example of the file chooser dialog box.
File chooser dialog box
Here are the steps needed to put up a file dialog box and recover what the user chooses from the box:
you need to supply a File object. File objects. All you need to know for now is that the constructor File(String filename) turns a file or directory name into a File object.
The only difference between these calls is the label of the “approve button,” the button that the user clicks to finish the file selection. You can also call the showDialog method and pass an explicit text for the approve button:
These calls return only when the user has approved, canceled, or dismissed the file dialog. The return value is JFile Chooser .APPROVE _OPTION, JFile Chooser .CANCEL _OPTION, or File Chooser .ERROR _OPTION
For the most part, these steps are simple. The major difficulty with using a file dialog is to specify a subset of files from which the user should choose. For example, suppose the user should choose a GIF image file. Then, the file chooser should only display files with extension .gif. It should also give the user some kind of feedback that the displayed files are of a particular category, such as “GIF Images.” But the situation can be more complex. If the user should choose a JPEG image file, then the extension can be either .jpg or .jpeg. Rather than coming up with a mechanism to codify these complexities, the designers of the file chooser supply a more elegant mechanism: to restrict the displayed files, you supply an object that extends the abstract class javax.swing.filechooser.FileFilter. The file chooser passes each file to the file filter and displays only the files that the file filter accepts.
At the time of this writing, two such subclasses are supplied: the default filter that accepts all files, and a filter that accepts all files with a given extension. Moreover, it is easy to write ad hoc file filters. You simply implement the two abstract methods of the FileFilter superclass:
The first method tests whether a file should be accepted. The second method returns a description of the file type that can be displayed in the file chooser dialog. Once you have a file filter object, you use the setFileFilter method of the JFileChooser class to install it into the file chooser object:
chooser .set File Filter (new File Name Extension Filter("Image files", "gif", "jpg");
You can install multiple filters to the file chooser by calling
The user selects a filter from the combo box at the bottom of the file dialog. By default, the “All files” filter is always present in the combo box. This is a good idea, just in case a user of your program needs to select a file with a nonstandard extension. However, if you want to suppress the “All files” filter, call chooser .set Accept AllFile Filter Used(false)
Finally, you can customize the file chooser by providing special icons and file descriptions for each file that the file chooser displays. You do this by supplying an object of a class extending the FileView class in the javax.swing.filechooser package. This is definitely an advanced technique. Normally, you don't need to supply a file view—the pluggable look and feel supplies one for you. But if you want to show different icons for special file types, you can install your own file view. You need to extend the FileView class and implement five methods:
Then you use the setFileView method to install your file view into the file chooser.The file chooser calls your methods for each file or directory that it wants to display. If your method returns null for the icon, name, or description, the file chooser then consults the default file view of the look and feel. That is good, because it means you need to deal only with the file types for which you want to do something different. The file chooser calls the isTraversable method to decide whether to open a directory when a user clicks on it. Note that this method returns a Boolean object, not a Boolean value! This seems weird, but it is actually convenient—if you aren't interested in deviating from the default file view, just return null. The file chooser will then consult the default file view. In other words, the method returns a Boolean to let you choose among three options: true (Boolean.TRUE), false (Boolean.FALSE), and don't care (null). The example program contains a simple file view class. That class shows a particular icon whenever a file matches a file filter. We use it to display a palette icon for all image files.
class FileIconView extends FileView
all this file view into your file chooser with the setFileView method:
The file chooser will then show the palette icon next to all files that pass the filter and use the default file view to show all other files. Naturally, we use the same filter that we set in the file chooser.
Finally, you can customize a file dialog by adding an accessory component. For example, Figure below shows a preview accessory next to the file list. This accessory displays a thumbnail view of the currently selected file.
A file dialog with a preview accessory
An accessory can be any Swing component. In our case, we extend the JLabel class and set its icon to a scaled copy of the graphics image:
There is just one challenge. We want to update the preview image whenever the user selects a different file. The file chooser uses the “JavaBeans” mechanism of notifying interested listeners whenever one of its properties changes. The selected file is a property that you can monitor by installing a Property Change Listener. Here is the code that you need to trap the notifications:
In our example program, we add this code to the ImagePreviewer constructor. Listing below contains a modification of the ImageViewer program in which the file chooser has been enhanced by a custom file view and a preview accessory.
As you saw in the preceding section, a high-quality file chooser is an intricate user interface component that you definitely do not want to implement yourself. Many user interface toolkits provide other common dialogs: to choose a date/time, currency value, font, color, and so on. The benefit is twofold. Programmers can simply use a high-quality implementation rather than rolling their own. And users have a common experience for these selections.
At this point, Swing provides only one additional chooser, the JColorChooser. You use it to let users pick a color value. Like the JFileChooser class, the color chooser is a component, not a dialog, but it contains convenience methods to create dialogs that contain a color chooser component.
Here is how you show a modal dialog with a color chooser:
Alternatively, you can display a modeless color chooser dialog. You supply the following:
The Swatches pane of a color chooser
The HSB pane of a color chooser
The RGB pane of a color chooser
Here is how you make a modeless dialog that sets the background color when the user clicks the OK button:
You can do even better than that and give the user immediate feedback of the color selection. To monitor the color selections, you need to obtain the selection model of the chooser and add a change listener:
In this case, there is no benefit to the OK and Cancel buttons that the color chooser dialog provides. You can just add the color chooser component directly into a modeless dialog:
This ends our discussion of user interface components
Core Java Related Interview Questions
|J2EE Interview Questions||Core Java Interview Questions|
|JDBC Interview Questions||JSP Interview Questions|
|Android Interview Questions||JavaServer Faces (JSF) Interview Questions|
|Java collections framework Interview Questions||Java 8 Interview Questions|
|Java Collections Interview Questions||Java Exception Handling Interview Questions|
|Java Concurrency Interview Questions||Java Serialization Interview Questions|
|Java Programmer Interview Questions||Java Inheritance Interview Questions|
|Java IO Interview Questions||Object Oriented Programming in PHP Interview Questions|
Core Java Tutorial
An Introduction To Java
The Java Programming Environment
Fundamental Programming Structures In Java
Objects And Classes
Interfaces And Inner Classes
User Interface Components With Swing
Deploying Applications And Applets
Exceptions, Logging, Assertions, And Debugging
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.