Monday, June 15, 2009

Java: JOptionPane Examples Part 4 - Complex

Break out of the JOptionPane Limitations with JDialog

In the final article in my JOptionPane example series, I will show how to eliminate a JOptionPane limitation that you may encounter. The limitation is size. Sure, the dialog automatically sizes itself to fit your GUI elements. However, there is no way to allow a user to resize the standard JOptionPane dialog.

The way to eliminate this problem is to embed a JOptionPane object within a JDialog. It's very simple and requires very little change to existing code you may have.

Example 1: Resizable and Editable JTextArea with JScrollPane scrollbars

This example expands upon Example 2 (from Part 2). A JTextArea is used, but the dialog is not resizable. By embedding with a JDialog, this limitation can be overcome.

The definition of the JTextArea and Object array remains the same:

    JTextArea area = new JTextArea();
area.setText("line1\nline2\nline3\nline4\nline5\nline6");
area.setRows(5);
area.setColumns(10);
area.setEditable(true);
JScrollPane scrollpane = new JScrollPane(area);

Object[] array = {
new JLabel("Enter some text:"),
scrollpane,
};
 

Instead of using one of the static methods of JOptionPane, a JOptionPane object is created using its constructor. The Object array and the message type are passed as arguments to the constructor.

    JOptionPane pane = new JOptionPane(array, JOptionPane.PLAIN_MESSAGE);
 

Once the JOptionPane object has been created, the createDialog() method is called, which returns a JDialog object. null is passed to createDialog() to center the dialog on the screen, while the string argument will be the title of the dialog.

    JDialog dialog = pane.createDialog(null, "Result Data");
 

Before the setVisible() method is called, setResizable() is called to allow the dialog to be resized. When setVisible() is called, the dialog will exhibit the same general behavior as when using the static methods of JOptionPane.

    dialog.setResizable(true);
dialog.setVisible(true);
 

Once the user has closed the dialog, control returns to the program. As with the original version of the program, the JTextArea object still exists and its value can be obtained using getText().

    String newtext = area.getText();
System.out.println( "newtext: " + newtext );
 

With JDialog, many new options are available.

2 comments:

Günter Zöchbauer said...

Good and simple explanation.
Just what I was looking for.

prashantgupta24 said...

This is simply one of the best blogs I've come across!! All features of such a trivial component are described so beautifully and aptly that no doubt remains in the mind..

Simply outstanding work! Hope other bloggers learn from this! :)