Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Swing Chapter 14. (The basics) Dialogs. Easy for reading, Click here!

Custom Search
Swing Chapter 14. (The basics) Dialogs. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 1/5 



Next Page (2/5) Next Page

Chapter 14. Dialogs

Subpages: 1. Dialogs and choosers overview 
2.
Adding an "About" dialog 
3.
JOptionPane message dialogs 
4. Customizing JColorChooser 
5. Customizing JFileChooser 

In this chapter:

  •          Dialogs and choosers overview
  •          Adding an "About" dialog
  •          JOptionPane message dialogs
  •          Customizing JColorChooser
  •          Customizing JFileChooser

14.1  Dialogs overview

Swing's JDialog class allows implementation of both modal and non-modal dialogs. In simple cases, when we need to post a short message or ask for a single value input, we can use standardized pre-built dialog boxes provided by the JOptionPane convenience class. Additionally, two special dialog classes provide powerful selection and navigation capabilities for choosing colors and files: JColorChooser and JFileChooser.

UI Guideline : Usage Advice When to Use a Dialog

Dialogs are intended for the acquisition of sets of related data. This may be the set of attributes for a particular object or group of objects. A Dialog is particularly useful when validation across those attributes must be performed before the data can be accepted. The validation code can be executed when an "accept" button is pressed and the dialog will only dismiss when the data is validated as good.

Dialogs are also useful for complex manipulations or selections. For example a dialog with two lists, "Available Players" and "Team for Saturday's Game," might allow the selection, addition, and deletion of items to and/or form each list. When the team for the Saturday game is selected, the User can accept the selection by pressing "OK".

Data entry and complex data manipulation which requires a clear boundary or definition of acceptance, are good uses for a dialog.

When to Use an Option Pane

Option Panes are designed for use when the system needs to hold a conversation with the User, either for simple directed data entry such as "Enter your name and password" or for navigation choices such as "View", "Edit", "Print".

When to Use a Chooser

Choosers have been introduced to facilitate consistency for common selections across a whole operating environment. If you have a need to select files or colors then you ought to be using the appropriate chooser. The User gets the benefit of only learning one component which appears again and again across applications. Using a Chooser when appropriate should improve customer acceptance for your application.

14.1.1 JDialog

class javax.swing.JDialog

This class extends java.awt.Dialog and is used to create a new dialog box in a separate native platform window. We typically extend this class to create our own custom dialog, as it is a container almost identical to JFrame.

Note: JDialog is a JRootPane container just as JFrame, and familiarity with chapter 3 is assumed here. All WindowEvents, default close operations, sizing and positioning, etc., can be controlled identically to JFrame and we will not repeat this material.

We can create a JDialog by specifying a dialog owner (Frame or Dialog instances), a dialog title, and a modal/non-modal state. The following code shows a typical custom dialog class constructor:

  class MyDialog extends JDialog

  {

    public MyDialog(Frame owner) {

      super(owner, "Sample Dialog", true);

      // Perform GUI initialization here

    }

  }

We are not required to pass a valid parent and are free to use null as the parent reference. As we discussed in chapter 2, the SwingUtilities class maintains a non-visible Frame instance registered with the AppContext service mapping, which is used as the parent of all null-parent dialogs. If a valid parent is used the dialog's icon will be that of the parent frame set with the setIconImage() method.

A modal dialog will not allow other windows to become active (i.e. respond to user input) at the same time it is active. Modal dialogs also block the invoking thread of execution and do not allow it to continue until they are dismissed. Non-modal dialogs do allow other windows to be active and do not affect the invoking thread.

To populate a dialog we use the same layout techniques discussed for JFrame, and we are prohibited from changing the layout or adding components directly. Instead we are expected to deal with the dialog's content pane:

    JButton btn = new JButton("OK");

    myDialog.getContentPane().add(btn);

From the design prospective, it is very common to add push buttons to a dialog. Typical buttons are "OK" or "Save" to continue with an action or save data, and "Cancel" or "Close" to close the dialog and cancel an action or avoid saving data.

Bug Alert! JDialog is not garbage collected even when it is disposed, made non-visible, and retains no direct references in scope. This 'feature' is not documented and is most likely an AWT or Swing bug.

Bug Alert! Because of certain AWT limitations, JDialog will only allow lightweight popup menus. JPopupMenu, and the components that use it, such as JComboBox and JMenu, can only be lightweight in modal dialogs. For this reason we need to be especially careful when implementing a modal dialog containing heavyweight components.

As with JFrame, JDialog will appear in the upper left-hand corner of the screen unless another location is specified. It is usually more natural to center a dialog with respect to its owner, as follows:

    Window owner = myDialog.getParent();

    myDialog.setResizable(false);

    Dimension d1 = myDialog.getSize();

    Dimension d2 = owner.getSize();

    int x = Math.max((d2.width-d1.width)/2, 0);

    int y = Math.max((d2.height-d1.height)/2, 0);

    myDialog.setBounds(x, y, d1.width, d1.height);

Note: It is common practice to show dialogs in response to menu selections. In such cases a menu's popup may remain visible and the parent frame needs to be manually repainted. For this reason we suggest calling repaint() on the parent before displaying dialogs invoked by menus.

To display a JDialog window we can use either the show() method inherited from java.awt.Dialog, or we can use the setVisible() method inherited from java.awt.Component. The following snippet code illustrates a typical scheme of creation and usage of the custom dialog box:

Reference: In chapter 20 we will show how to construct quite complex dialogs and assume knowledge of the JDialog information presented here. We suggest supplementing this chapter's material with a brief look at the chapter 20 examples to get a feel for what lies ahead.

Note: When building complex dialogs it is normally preferable that one instance of that dialog be used throughout a given Java session. We suggest instiating such dialogs when the application/applet is started, and storing them as variables for repetitive use. This avoids the often significantly long delay time required to instantiate a dialog each time it is needed. We also suggest wrapping dialog instantiation in a separate thread to avoid clogging up the AWT event dispatching thread.

14.1.2  JOptionPane

class javax.swing.JOptionPane

This class provides an easy and convenient way to display standard dialogs used for posting a message, asking a question, or prompting for simple user input. Note that each JOptionPane dialog is modal and will block the invoking thread of execution, as described above (this does not apply to internal dialogs; we will discuss these soon enough).

It is important to understand that JOptionPane is not itself a dialog (note that it directly extends JComponent). Rather, it acts as a container that is normally placed in a JDialog or a JInternalFrame, and provides several convenient methods for doing so. There is nothing stopping us from creating a JOptionPane and placing it in any container we choose, but this will rarely be useful. Figure 14.1 illustrates the general JOptionPane component arrangement:

Figure 14.1 The components of a JOptionPane dialog.

<<file figure14-1.gif>>

JOptionPane class supports four pre-defined types: Message, Confirm, Input, and Option. We will discuss how to create and work with each type, but first we need to understand the constituents. To create a JOptionPane that is automatically placed in either a JDialog or JInternalFrame, we need to supply some or all of the following parameters to one if its static showXXDialog() methods (discussed below):

A parent Component. If the parent is Frame, the option pane will be placed in a JDialog and be centered with respect to the parent. If this parameter is null, it will instead be centered with respect to the screen. If the parent is a JDesktopPane, or is contained in one, the opyion pane will be contained in a JInternalFrame and placed in the parent desktop's MODAL_LAYER (see chapter 15). For other types of parent components a JDialog will be used and placed below that component on the screen.

A message Object: a message to be displayed in the center of the pane (in the Message area). Typically this is a String, which may be broken into separate lines using '\n' characters. However this parameter has a generic Object type and JOptionPane deals with non-String objects in the following way:

Icon: will be displayed in a JLabel.

Component: will simply be placed in the message area.

Object[]: dealt with as described here, these will be placed vertically in a column (this is done recursively).

Object: the toString() method will be called to convert this to a String for display in a JLabel

An int message type: can be one of the following static constants defined in JOptionPane: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, PLAIN_MESSAGE. This is used by the current L&F to customize the look of an option pane by displaying an appropriate icon (in the Icon area) corresponding to the message type's meaning (see below).

An int option type: can be one of the following static constants defined in JOptionPane: DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION. This parameter specifies a set of corresponding buttons to be displayed at the bottom of the pane (in the Options area). Another set of similar parameters returned from JOptionPane showXXDialog() methods (see below) specify which button was pressed: CANCEL_OPTION, CLOSED_OPTION, NO_OPTION, OK_OPTION, YES_OPTION. Note that CLOSED_OPTION is only returned when the pane is contained in a JDialog or JInternalFrame, and that container's close button (located in the title bar) is pressed.

An Icon: displayed in the left side of the pane (in the Icon area). If not explicitly specified, the icon is determined by the current L&F based on the message type (this does not apply to panes using the PLAIN_MESSAGE message type).

An array of option Objects: we can directly specify an array of option Objects to be displayed at the bottom of the pane (in the Options area). This array can also be specified with the setOptions() method. It typically contains an array of Strings to be displayed on a JButtons, but JOptionPane also honors Icons (also displayed in JButtons) and Components (placed directly in a row). Similar to message Objects, the toString() method will be called to convert all objects that are not Icon's or Components to a String for display in a JButton. If null is used, the option buttons are determined by the specified option type.

An initial value Object: specifies which button or component in the Options area has the focus when the pane is initially displayed.

An array of selection value Objects: specifies an array of allowed choices the user can make. If this array contains more than twenty items a JList is used to display them using the default rendering behavior (see chapter 10). If the array contains less than twenty items a JComboBox is used to display them (also using the default JList rendering behavior). If null is used, an empty JTextField is displayed. In any case, the component used for selection is placed in the Input area.

A String title: used for display as the titlebar title in the containing JDialog or JInternalFrame.

The following static methods are provided for convenient creation of JOptionPanes placed in JDialogs:

showConfirmDialog(): this method displays a dialog with several buttons and returns an int option type corresponding to the button pressed (see above). Four overloaded methods are provided allowing specification of, at most, a parent component, message, title, option type, message type, and icon.

showInputDialog(): this method displays a dialog which is intended to receive user input, and returns a String (if the input component is a text field) or an Object if the input component is a list or a combo box (see above). Four overloaded methods are provided allowing specification of, at most, a parent component, message, title, option type, message type, icon, array of possible selections, and an initially selected item. Two buttons are always displayed in the Options area: "OK" and "Cancel."

showMessageDialog(): this method displays a dialog with an "OK" button, and doesn't return anything. Three overloaded methods are provided allowing specification of, at most, a parent component, message, title, message type, and icon.

showOptionDialog(): this method displays a dialog which can be customized a bit more than the above dialogs, and returns either the index into the array of option Objects specified, or an option type if no option Objects are specified. Only one method is provided allowing specification of a parent component, message, title, option type, message type, icon, array of option Objects, and an option Object with the initial focus. The option Objects are layed out as a row in the Options area.

To create JOptionPanes contained in JInternalFrames rather than JDialogs, we can use the showInternalConfirmDialog(), showInternalInputDialog(), showInternalMessageDialog(), and showInternalOptionDialog() overloaded methods. These work the same as the methods described above, only they expect that a given parent is a JDesktopPane (or has a JDesktopPane ancestor).

Note: Internal dialogs are not modal and, as such, do not block execution of the invoking thread.

Alternatively, we can directly create a JOptionPane as illustrated by the following psuedo-code:

    JOptionPane pane = new JOptionPane(...); // Specify parameters

    pane.setXX(...); // Set additional parameters

    JDialog dialog = pane.createDialog(parent, title);

    dialog.show();

    Object result = pane.getValue();

    // Process result (may be null)

This code creates an instance of JOptionPane and specifies several parameters (see API docs). Additional settings are then provided with setXX accessor methods. The createDialog() method creates a JDialog instance containing our JOptionPane which is then displayed (we could also have used the createInternalFrame() method to wrap our pane in a JInternalFrame). Finally, the getValue() method retrieves the option selected by user, so the program may react accordingly. This value may be null (if the user closes dialog window). Note that because program execution blocks until the dialog is dismissed, getValue() will not be called until a selection is made.

Note: The advantage of JOpionPane is its simplicity and convenience. In general, there should be no need to customize it to any large extent. If you find yourself desiring a different layout we suggest writing your own container instead.

Figure 14.2 illustrates the use of JOptionPane where a custom dialog may be more suitable. Note the extremely long button, text field, and combo box. Such extreme sizes have detrimental affects on the overall usability and appearance of an app.

Figure 14.2 Awkward use of components in a JOptionPane.

<<file figure14-2.gif>>

UI Guideline : Usage of JOptionPane

JOptionPane is not designed as a general purpose input dialog. The primary restriction is the defined layout. JOptionPane is designed for use in conversations between the System and the User where the desired result is a navigation choice or a data selection, or where the User must be notified of an event.

Therefore, JOptionPane is best used with a single entry field or combobox selection, possibly with a set of buttons for selection or navigational choice.

For example an Answer Phone application might require an option dialog displaying "You have 1 message," with options "Play," "Save," "Record outgoing message," and "Delete messages." Such a requirement can be met with a JOptionPane which provides a single label for the message and 4 buttons for each of the choices available.

14.1.3  JColorChooser

class javax.swing.JColorChooser

This class represents a powerful, pre-built component used for color selection. JColorChooser is normally used in a modal dialog. It consists of tabbed pane containing three panels each offering a different method of choosing a color: Swatches, HSB, and RGB. A color preview pane is displayed below this tabbed pane and always displays the currently selected color. Figure 14.3 illustrates.

Figure 14.3 JColorChooser in a JDialog.

<<file figure14-3.gif>>

The static showDialog() method instatiates and displays a JColorChooser in a modal dialog, and returns the selected Color (or null if no selection is made):

    Color color =  JColorChooser.showDialog(myComponent,

      "Color Chooser", Color.red);

    if (color != null)

      myComponent.setBackground(c);

A more complex variant is the static createDialog() method which allows specification of two ActionListeners to be invoked when a selection is made or cancelled respectively. We can also do the following:

Retrieve color selection panels with the getChooserPanels() method and use them outside the dialog.

Add custom color selection panels using the addChooserPanel() method.

Assign a new custom color preview pane uwing the setPreviewPanel() method.

Several classes and interfaces supporting JColorChooser are grouped into the javax.swing.colorchooser package.

14.1.4  The ColorSelectionModel interface

abstract interface javax.swing.colorchooser.ColorSelectionModel

This is a simple interface describing the color selection model for JColorChooser. It declares methods for adding and removing ChangeListeners which are intended to be notified when the selected Color changes, and getSelectedColor()/setSelectedColor() accessors to retrieve and assign the currently selected Color respectively.

14.1.5 DefaultColorSelectionModel

class javax.swing.colorchooser.DefaultColorSelectionModel

This is the default concrete implementation of the ColorSelectionModel interface. It simply implements the necessary methods as expected, stores registered ChangeListeners in an EventListenerList, and implements an additional method to perform the actual firing of ChangeEvents to all registered listeners.

14.1.6 AbstractColorChooserPanel

abstract class javax.swing.colorchooser.AbstractColorChooserPanel

This abstract class describes a color chooser panel which can be added to JColorChooser as a new tab. We can sub-class AbstractColorChooserPanel to implement a custom color chooser panel of our own. The two most important methods that must be implemented are buildChooser() and updateChooser(). The former is normally called only once at instantiation time and is intended to perform all GUI initialization tasks. The latter is intended to update the panel to reflect a change in the associated JColorChooser's ColorSelectionModel. Other required methods include those allowing access to a display name and icon used to identify the panel when it is displayed in JColorChooser's tabbed pane.

14.1.7 ColorChooserComponentFactory

class javax.swing.colorchooser.ColorChooserComponentFactory

This is a very simple class that is responsible for creating and returning instances of the default color chooser panels and preview panel used by JColorChooser. The three color chooser panels are instances of private classes: DefaultSwatchChooserPanel, DefaultRGBChooserPanel, DefaultHSBChooserPanel. The preview pane is an instance of DefaultPreviewPane. Other private classes used in this package include two custom layout managers, CenterLayout and SmartGridLayout, a class for convenient generation of synthetic images, SyntheticImage, and a custom text field that only allows integer input, JIntegerTextField. These undocumented classes are very interesting and we urge curious readers to spend some time with the source code. Because they are only used within the colorchooser package and are defined as package private, we will not discuss them further here.

14.1.8 JFileChooser

class javax.swing.JFileChooser

This class represents the standard Swing directory navigation and file selection component which is normally used in a modal dialog. It consists of a JList and several button and input components all linked together offering functionality similar to the file dialogs we are used to on our native platforms. The JList is used to display a list of files and sub-driectories residing in the current directory being navigated. Figure 14.4 illustrates.

Figure 14.4 JFileChooser in a JDialog.

<<file figure14-4.gif>>

UI Guideline : Cross Application Consistency

The key reason for promoting the use of a standard file chooser dialog is to promote the consistency of such an operation across the whole operating system or machine environment. The User experience is improved because file selection is always the same no matter which application they are running. This is an important goal and worthy of recognition. Thus, if you have a requirement to manipulate files, you ought to be using the JFileChooser component.

The fact that such a re-usable component exists and much of the complex coding is provided as part of the implementation, is merely a bonus for the developer.

We can set the current directory by passing a String to its setCurrentDirectory() method. JFileChooser also has the ability to use special FileFilters (discussed below) to only allow navigation of certain types of files. Several properties control whether directories and/or files can be navigated and selected, and how the typical "Open" (approve) and "Cancel" (cancel) buttons are represented (see the API docs for more on these straight forward methods.)

To use this component we normally create an instance of it, set the desired options, and call showDialog() to place it in an active modal dialog. This method takes the parent component and the text to display for its approve button, as parameters. Calling showOpenDialog()or showSaveDialog()will show a modal dialog with "Open" or "Save" for the approve button text respectively.

Note: JFileChooser can take a significant amount of time to instantiate. Please consider storing an instance as a variable and performing instantiation in a separate thread at startup time, as discussed in a note above.

The following code instantiates a JFileChooser in an "Open" file dialog, verifies that a valid file is selected, and retrieves that file as a File instance:

    JFileChooser chooser = new JFileChooser();

    chooser.setCurrentDirectory(".");

    if (chooser.showOpenDialog(myComponent) !=

      JFileChooser.APPROVE_OPTION)

        return;

    File file = chooser.getSelectedFile();

JFileChooser generates PropertyChangeEvents when any of its properties change state. The approve and cancel buttons generate ActionEvents when pressed. We can register PropertyChangeListeners and ActionListeners to receive these events respectively. As any well-defined JavaBean should, JFileChooser defines several static String constants corresponding to each property name, e.g. JFileChooser.FILE_FILTER_CHANGED_PROPERTY (see API docs for a full listing). We can use these constants in determining which property a JFileChooser-generated PropertyChangeEvent corresponds to.

JFileChooser also supports the option of inserting an accessory component. This component can be any component we like and will be placed to the right of the JList. In constructing such a component, we are normally expected to implement the PropertyChangeListener interface. This way the component can be registered with the associated JFileChooser to receive notification of property state changes. The component should use these events to update its state accordingly. We use the setAccessory() method to assign an accessory component to a JFileChooser, and addPropertyChangeListener() to register it for receiving property state change notification.

Reference: For a good example of an accessory component used to preview selected images, see the FileChooserDemo example that ships with Java 2. In the final example of this chapter we will show how to customize JFileChooser in a more direct mannar.

Several classes and interfaces related to JFileChooser are grouped into javax.swing.filechooser package.

Note: JFileChooser is still fairly immature. For example, multi-selection mode is specified but has not been implemented yet. Later in this chapter we will show how to work around this, as well as how to build our own accessory-like component in a different location than that of a normal accessory as described above.

14.1.9  FileFilter

abstract class javax.swing.filechooser.FileFilter

This abstract class is used to implement a filter for displaying only certain file types in JFileChooser. Two methods must be implemented in concrete sub-classes:

boolean accept(File f): returns true if the given file should be displayed, false otherwise.

String getDescription(): returns a description of the filter used in the JComboBox at the bottom of JFileChooser.

To manage FileFilters we can use several methods in JFileChooser, including:

addChoosableFileFilter(FileFilter f) to add a new filter.

removeChoosableFileFilter(FileFilter f) to remove an existing filter.

setFileFilter(FileFilter f) to set a filter as currently active (and append it, if necessary).

By default JFileChooser receives a filter accepting all files. Special effort must be made to remove this filter if we do not desire our application to accept all files:

    FileFilter ft = myChooser.getAcceptAllFileFilter();

    myChooser.removeChoosableFileFilter(ft);

So how do we create a simple file filter instance to only allow navigation and selection of certain file types? The following class can be used as template for defining most of our own filters, and we will see it used in future chapters:

  class SimpleFilter extends FileFilter

  {

    private String m_description = null;

    private String m_extension = null;

    public SimpleFilter(String extension, String description) {

      m_description = description;

      m_extension = "." + extension.toLowerCase();

    }

    public String getDescription() {

      return m_description;

    }

    public boolean accept(File f) {

      if (f == null)

        return false;

      if (f.isDirectory())

        return true;

      return f.getName().toLowerCase().endsWith(m_extension);

    }

  }

Note that we always return true for directories because we normally always want to be able to navigate any directory. This filter only shows files matching the given extension String passed into our constructor and stored as variable m_extension. In more robust, multi-purpose filters we might store an array of legal extensions, and check for each in the accept() method. Also note that the description String passed into the constructor, and stored as variable m_description, is the String shown in the combo box at the bottom of JFileChooser representing the corresponding file type. JFileChooser can maintain multiple filters, all added using the addChoosableFileFilter() method, and removable with its removeChoosableFileFilter() method.

14.1.10            FileSystemView

abstract class javax.swing.filechooser.FileSystemView

This class encapsulates functionality which extracts information about files, directories, and partitions, and supplies this information to the JFileChooser component. This class is used to make JFileChooser independent from both platform-specific file system information, as well as the JDK/Java 2 release version (since the JDK1.1 File API doesn't allow access to some more specific file information available in Java 2). We can provide our own FileSystemView sub-class and assign it to a JFileChooser instance using the setFileSystemView(FileSystemView fsv) method. Four abstract methods must be implemented:

createNewFolder(File containingDir): creates a new folder (directory) within the given folder.

getRoots(): returns all root partitions. The notion of a root differs significantly from platform to platform.

isHiddenFile(File f): returns whether or not the given File is hidden.

isRoot(File f): returns whether or not the given File is a partition or drive.

These methods are called by JFileChooser and FileFilter implementations and we will, in general, have no need to extend this class unless we need to tweak the way JFileChooser interacts with our OS. The static getFileSystemView() method currently returns a Unix or Windows specific instance for use by JFileChooser in the most likely event that one of these platform types is detected. Otherwise, a generic instance is used. Support for Macintosh, OS2, and several other operating systems is expected to be provided here in future releases.

14.1.11            FileView

abstract class javax.swing.filechooser.FileView

This abstract class can be used to provide customized information about files and their types (typically determined by the file extension), including icons and a string description. Each L&F provides its own sub-class of FileView, and we can construct our own fairly easily. Each of the five methods in this class is abstract and must be implemented by sub-classes. The following generalized template can be used when creating our own FileViews:

  class MyExtView extends FileView

  {

    // Store icons to use for list cell renderer.

    protected static ImageIcon MY_EXT_ICON =

      new ImageIcon("myexticon.gif");

    protected static ImageIcon MY_DEFAULT_ICON =

      new ImageIcon("mydefaulticon.gif");

    // Return the name of a given file. "" corresponds to

    // a partition, so in this case we must return the path.

    public String getName(File f) {

      String name = f.getName();

      return name.equals("") ? f.getPath() : name;

    }

    // Return the description of a given file.

    public String getDescription(File f) {

      return getTypeDescription(f);

    }

    // Return the String to use for representing each specific

    // file type.  (Not used by JFileChooser in Java 2 FCS)

    public String getTypeDescription(File f) {

      String name = f.getName().toLowerCase();

      if (name.endsWith(".ext"))

        return "My custom file type";

      else

        return "Unrecognized file type";

    }

    // Return the icon to use for representing each specific

    // file type in JFileChooser's JList cell renderer.

    public Icon getIcon(File f) {

      String name = f.getName().toLowerCase();

      if (name.endsWith(".ext"))

        return MY_EXT_ICON;

      else

        return MY_DEFAULT_ICON;

    }

    // Normally we should return true for directories only.

    public Boolean isTraversable(File f) {

      return (f.isDirectory() ? Boolean.TRUE : Boolean.FALSE);

    }

  }

We will see how to build a custom FileView for JAR and ZIP archive files in the final example of this chapter.



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy