Java Open a Dialog Again Until Condition Is Met

A Dialog window is an independent sub window meant to conduct temporary discover apart from the main Swing Awarding Window. Most Dialogs nowadays an fault message or warning to a user, but Dialogs tin present images, directory trees, or just nigh anything compatible with the main Swing Awarding that manages them.

For convenience, several Swing component classes tin directly instantiate and display dialogs. To create simple, standard dialogs, you use the JOptionPane grade. The ProgressMonitor class tin put upward a dialog that shows the progress of an functioning. Two other classes, JColorChooser and JFileChooser, likewise supply standard dialogs. To bring up a print dialog, you tin employ the Printing API. To create a custom dialog, utilise the JDialog class directly.

The code for unproblematic dialogs can be minimal. For example, here is an informational dialog:

An informational dialog requires minimal code

Here is the lawmaking that creates and shows it:

JOptionPane.showMessageDialog(frame, "Eggs are not supposed to exist green.");          

The remainder of this section covers the post-obit topics:

  • An Overview of Dialogs
  • The DialogDemo Example
  • JOptionPane Features
  • Creating and Showing Simple Dialogs
  • Customizing Button Text
  • Getting the User'south Input from a Dialog
  • Stopping Automatic Dialog Closing
  • The Dialog API
  • Examples that Use Dialogs

An Overview of Dialogs

Every dialog is dependent on a Frame component. When that Frame is destroyed, and then are its dependent Dialogs. When the frame is iconified, its dependent Dialogs also disappear from the screen. When the frame is deiconified, its dependent Dialogs return to the screen. A swing JDialog class inherits this behavior from the AWT Dialog grade.

A Dialog can be modal. When a modal Dialog is visible, it blocks user input to all other windows in the programme. JOptionPane creates JDialogs that are modal. To create a not-modal Dialog, you must use the JDialog class directly.

Starting with JDK vii, you tin modify dialog window modality behavior using the new Modality API. Run into The New Modality API for details.

The JDialog class is a subclass of the AWT coffee.awt.Dialog class. Information technology adds a root pane container and support for a default close operation to the Dialog object . These are the aforementioned features that JFrame has, and using JDialog directly is very similar to using JFrame. If you're going to utilise JDialog direct, and so yous should understand the fabric in Using Top-Level Containers and How to Brand Frames, peculiarly Responding to Window-Closing Events.

Fifty-fifty when you lot utilize JOptionPane to implement a dialog, yous're still using a JDialog backside the scenes. The reason is that JOptionPane is simply a container that tin automatically create a JDialog and add together itself to the JDialog's content pane.

The DialogDemo Example

Here is a motion-picture show of an application that displays dialogs.

DialogDemo lets you bring up many kinds of dialogs

Attempt this::

  1. Click the Launch button to run the Dialog Demo using Coffee™ Spider web Beginning (download JDK seven or after). Alternatively, to compile and run the example yourself, consult the example alphabetize.Launches the DialogDemo example
  2. Click the Show it! push.
    A modal dialog will appear. Until you close it, the application will exist unresponsive, although it volition repaint itself if necessary. Yous tin can close the dialog either by clicking a push in the dialog or explicitly, such as by using the dialog window decorations.
  3. In the More Dialogs pane, click the bottom radio button and and so the Bear witness it! button.
    A non-modal dialog will announced. Note that the DialogDemo window remains fully functional while the non-modal dialog is up.
  4. While the not-modal dialog is showing, iconify the DialogDemo window.
    The dialog volition disappear from the screen until you deiconify the DialogDemo window.

JOptionPane Features

Using JOptionPane, you can quickly create and customize several dissimilar kinds of dialogs. JOptionPane provides support for laying out standard dialogs, providing icons, specifying the dialog title and text, and customizing the button text. Other features permit you to customize the components the dialog displays and specify where the dialog should appear onscreen. You can fifty-fifty specify that an choice pane put itself into an internal frame (JInternalFrame) instead of a JDialog.

When you create a JOptionPane, look-and-feel-specific code adds components to the JOptionPane and determines the layout of those components.

JOptionPane's icon support lets yous easily specify which icon the dialog displays. Y'all can use a custom icon, no icon at all, or whatever one of 4 standard JOptionPane icons (question, information, alert, and error). Each look and experience has its own versions of the four standard icons. The following figure shows the icons used in the Java (and Windows) expect and feel.

Icons used by JOptionPane
Icon description Coffee look and feel Windows await and experience
question The Java look and feel icon for dialogs that ask questions The Windows look and feel icon for dialogs that ask questions
information The Java look and feel icon for informational dialogs The Windows look and feel icon for informational dialogs
warning The Java look and feel icon for warning dialogs The Windows look and feel icon for warning dialogs
mistake The Java look and feel icon for error dialogs The Windows look and feel icon for error dialogs

Creating and Showing Elementary Dialogs

For nearly simple modal dialogs, you create and evidence the dialog using one of JOptionPane's showXxxDialog methods. If your dialog should be an internal frame, then add together Internal subsequently show — for example, showMessageDialog changes to showInternalMessageDialog. If yous need to control the dialog window-closing behavior or if yous do non desire the dialog to be modal, so you should directly instantiate JOptionPane and add it to a JDialog instance. Then invoke setVisible(true) on the JDialog to make it appear.

The two virtually useful showXxxDialog methods are showMessageDialog and showOptionDialog. The showMessageDialog method displays a elementary, one-button dialog. The showOptionDialog method displays a customized dialog — information technology can display a diverseness of buttons with customized push button text, and can contain a standard text message or a collection of components.

The other two showXxxDialog methods are used less oft. The showConfirmDialog method asks the user to confirm something, but presents standard button text (Yes/No or the localized equivalent, for example) rather than push text customized to the user situation (Start/Cancel, for instance). A 4th method, showInputDialog, is designed to display a modal dialog that gets a string from the user, using either a text field, an uneditable combo box or a list.

Here are some examples, taken from DialogDemo.java, of using showMessageDialog, showOptionDialog, and the JOptionPane constructor. For more example code, see DialogDemo.java and the other programs listed in Examples that Apply Dialogs.

showMessageDialog
Displays a modal dialog with one button, which is labeled "OK" (or the localized equivalent). You lot tin can easily specify the message, icon, and title that the dialog displays. Hither are some examples of using showMessageDialog:
Informational dialog with default title and icon
//default championship and icon JOptionPane.showMessageDialog(frame,     "Eggs are not supposed to be light-green.");                      
Informational dialog with custom title, warning icon
//custom title, warning icon JOptionPane.showMessageDialog(frame,     "Eggs are non supposed to exist greenish.",     "Inane warning",     JOptionPane.WARNING_MESSAGE);                      
Informational dialog with custom title, error icon
//custom title, error icon JOptionPane.showMessageDialog(frame,     "Eggs are not supposed to exist green.",     "Inane mistake",     JOptionPane.ERROR_MESSAGE);                      
Informational dialog with custom title, no icon
//custom title, no icon JOptionPane.showMessageDialog(frame,     "Eggs are not supposed to be dark-green.",     "A plain message",     JOptionPane.PLAIN_MESSAGE);                      
Informational dialog with custom title, custom icon
//custom title, custom icon JOptionPane.showMessageDialog(frame,     "Eggs are not supposed to be dark-green.",     "Inane custom dialog",     JOptionPane.INFORMATION_MESSAGE,     icon);                      
showOptionDialog
Displays a modal dialog with the specified buttons, icons, message, title, and so on. With this method, you can alter the text that appears on the buttons of standard dialogs. You tin as well perform many other kinds of customization.
Yes/No/Cancel (in different words); showOptionDialog
//Custom button text Object[] options = {"Yes, please",                     "No, thanks",                     "No eggs, no ham!"}; int northward = JOptionPane.showOptionDialog(frame,     "Would y'all like some light-green eggs to get "     + "with that ham?",     "A Silly Question",     JOptionPane.YES_NO_CANCEL_OPTION,     JOptionPane.QUESTION_MESSAGE,     null,     options,     options[2]);                      
JOptionPane (constructor)
Creates a JOptionPane with the specified buttons, icons, bulletin, title, and then on. You must then add the option pane to a JDialog, register a property-change listener on the option pane, and show the dialog. See Stopping Automated Dialog Endmost for details.
Explicitly used the JOptionPane constructor
terminal JOptionPane optionPane = new JOptionPane(     "The only mode to shut this dialog is by\n"     + "pressing one of the following buttons.\n"     + "Practice you understand?",     JOptionPane.QUESTION_MESSAGE,     JOptionPane.YES_NO_OPTION);                      

The arguments to all of the showXxxDialog methods and JOptionPane constructors are standardized, though the number of arguments for each method and constructor varies. The following list describes each statement. To come across the verbal list of arguments for a particular method, come across The Dialog API.

Component parentComponent
The first argument to each bear witness30Dialog method is always the parent component, which must be a Frame, a component inside a Frame, or null. If you specify a Frame or Dialog, so the Dialog volition appear over the eye of the Frame and follow the focus behavior of that Frame. If you specify a component inside a Frame, and then the Dialog will appear over the center of that component and will follow the focus beliefs of that component'south Frame. If y'all specify null, then the look and experience will pick an appropriate position for the dialog — mostly the centre of the screen — and the Dialog will not necessarily follow the focus behavior of any visible Frame or Dialog.

The JOptionPane constructors do not include this argument. Instead, you specify the parent frame when yous create the JDialog that contains the JOptionPane, and you employ the JDialog setLocationRelativeTo method to set the dialog position.

Object message
This required argument specifies what the dialog should brandish in its main area. Generally, you specify a string, which results in the dialog displaying a label with the specified text. You can split the message over several lines by putting newline (\n) characters within the bulletin string. For example:
"Complete the sentence:\n \"Dark-green eggs and...\""              
Cord championship
The championship of the dialog.
int optionType
Specifies the set up of buttons that appear at the bottom of the dialog. Choose from one of the post-obit standard sets: DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION.
int messageType
This statement determines the icon displayed in the dialog. Choose from one of the following values: PLAIN_MESSAGE (no icon), ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE.
Icon icon
The icon to display in the dialog.
Object[] options
Generally used to specify the string displayed by each push button at the bottom of the dialog. See Customizing Button Text in a Standard Dialog for more information. Can as well be used to specify icons to be displayed past the buttons or non-button components to be added to the button row.
Object initialValue
Specifies the default value to be selected.

You can either let the pick pane display its default icon or specify the icon using the message type or icon argument. Past default, an option pane created with showMessageDialog displays the data icon, one created with showConfirmDialog or showInputDialog displays the question icon, and 1 created with a JOptionPane constructor displays no icon. To specify that the dialog display a standard icon or no icon, specify the message type corresponding to the icon you desire. To specify a custom icon, utilize the icon argument. The icon argument takes precedence over the bulletin blazon; every bit long as the icon statement has a non-null value, the dialog displays the specified icon.

Customizing Button Text

When you use JOptionPane to create a dialog, you can either utilise the standard button text (which might vary by expect and experience and locale) or specify different text. By default, the option pane type determines how many buttons appear. For example, YES_NO_OPTION dialogs have two buttons, and YES_NO_CANCEL_OPTION dialogs take three buttons.

The following code, taken from DialogDemo.java, creates two Yes/No dialogs. The first dialog is implemented with showConfirmDialog, which uses the expect-and-feel diction for the 2 buttons. The 2d dialog uses showOptionDialog then information technology can customize the wording. With the exception of diction changes, the dialogs are identical.

A yes/no dialog, in those words [but perhaps translated]
//default icon, custom title int due north = JOptionPane.showConfirmDialog(     frame,     "Would you similar light-green eggs and ham?",     "An Inane Question",     JOptionPane.YES_NO_OPTION);                  
A yes/no dialog -- in other words
Object[] options = {"Yes, delight",                     "No way!"}; int n = JOptionPane.showOptionDialog(frame,     "Would you like green eggs and ham?",     "A Light-headed Question",     JOptionPane.YES_NO_OPTION,     JOptionPane.QUESTION_MESSAGE,     zero,     //do not use a custom Icon     options,  //the titles of buttons     options[0]); //default button championship                  

Equally the previous code snippets showed, the showMessageDialog, showConfirmDialog, and showOptionDialog methods return an integer indicating the user'southward choice. The values for this integer are YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION, and CLOSED_OPTION. Except for CLOSED_OPTION, each selection corresponds to the button the user pressed. When CLOSED_OPTION is returned, it indicates that the user airtight the dialog window explicitly, rather than by choosing a button inside the option pane.

Even if you lot change the strings that the standard dialog buttons display, the return value is notwithstanding one of the pre-divers integers. For case, a YES_NO_OPTION dialog always returns one of the following values: YES_OPTION, NO_OPTION, or CLOSED_OPTION.

Getting the User's Input from a Dialog

The only form of showXxxDialog that does non return an integer is showInputDialog, which returns an Object instead. This Object is more often than not a Cord reflecting the user's choice. Hither is an case of using showInputDialog to create a dialog that lets the user choose ane of 3 strings:

An input dialog with a combo box
Object[] possibilities = {"ham", "spam", "yam"}; Cord south = (Cord)JOptionPane.showInputDialog(                     frame,                     "Consummate the sentence:\due north"                     + "\"Greenish eggs and...\"",                     "Customized Dialog",                     JOptionPane.PLAIN_MESSAGE,                     icon,                     possibilities,                     "ham");  //If a cord was returned, say so. if ((southward != zippo) && (s.length() > 0)) {     setLabel("Green eggs and... " + s + "!");     render; }  //If you're hither, the return value was null/empty. setLabel("Come on, stop the sentence!");          

If you do non care to limit the user's choices, you can either employ a form of the showInputDialog method that takes fewer arguments or specify nada for the array of objects. In the Java look and feel, substituting null for possibilities results in a dialog that has a text field and looks like this:

An input dialog with a text field

Considering the user can type annihilation into the text field, you might want to check the returned value and ask the user to try once more if it is invalid. Some other arroyo is to create a custom dialog that validates the user-entered data before it returns. See CustomDialog.java for an instance of validating data.

If you're designing a custom dialog, you lot need to design your dialog's API so that you can query the dialog virtually what the user chose. For example, CustomDialog has a getValidatedText method that returns the text the user entered.

Stopping Automatic Dialog Endmost

By default, when the user clicks a JOptionPane-created push button, the dialog closes. But what if you lot want to check the user's reply earlier closing the dialog? In this example, you must implement your ain holding alter listener so that when the user clicks a button, the dialog does non automatically shut.

DialogDemo contains two dialogs that implement a property change listener. One of these dialogs is a custom modal dialog, implemented in CustomDialog, that uses JOptionPane both to go the standard icon and to get layout help. The other dialog, whose code is below, uses a standard Yep/No JOptionPane. Though this dialog is rather useless every bit written, its lawmaking is simple plenty that you lot can use it equally a template for more complex dialogs.

Besides setting the property change listener, the following lawmaking also calls the JDialog'due south setDefaultCloseOperation method and implements a window listener that handles the window shut attempt properly. If you do not care to be notified when the user closes the window explicitly, and so ignore the bold code.

concluding JOptionPane optionPane = new JOptionPane(                 "The just style to close this dialog is past\n"                 + "pressing i of the post-obit buttons.\n"                 + "Do you understand?",                 JOptionPane.QUESTION_MESSAGE,                 JOptionPane.YES_NO_OPTION);  final JDialog dialog = new JDialog(frame,                               "Click a push button",                              true); dialog.setContentPane(optionPane);            dialog.setDefaultCloseOperation(     JDialog.DO_NOTHING_ON_CLOSE); dialog.addWindowListener(new WindowAdapter() {     public void windowClosing(WindowEvent we) {         setLabel("Thwarted user attempt to shut window.");     } });            optionPane.addPropertyChangeListener(     new PropertyChangeListener() {         public void propertyChange(PropertyChangeEvent eastward) {             String prop = e.getPropertyName();              if (dialog.isVisible()               && (e.getSource() == optionPane)              && (prop.equals(JOptionPane.VALUE_PROPERTY))) {                 //If you lot were going to check something                 //before closing the window, you lot'd exercise                 //information technology here.                 dialog.setVisible(fake);             }         }     }); dialog.pack(); dialog.setVisible(true);  int value = ((Integer)optionPane.getValue()).intValue(); if (value == JOptionPane.YES_OPTION) {     setLabel("Good."); } else if (value == JOptionPane.NO_OPTION) {     setLabel("Try using the window decorations "              + "to close the non-auto-closing dialog. "              + "You can't!"); }          

The Dialog API

The following tables list the usually used JOptionPane and JDialog constructors and methods. Other methods you're probable to call are divers by the Dialog, Window and Component classes and include pack, setSize, and setVisible.

The API is listed as follows:

  • Showing Standard Modal Dialogs (using JOptionPane Class Methods)
  • Methods for Using JOptionPanesouthward Directly
  • Frequently Used JDialog Constructors and Methods
Showing Standard Modal Dialogs (Using JOptionPane Course Methods)
Method Purpose
static void showMessageDialog(Component, Object)
static void showMessageDialog(Component, Object, String, int)
static void showMessageDialog(Component, Object, String, int, Icon)
Testify a i-button, modal dialog that gives the user some data. The arguments specify (in order) the parent component, message, title, message type, and icon for the dialog. See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.
static int showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object) Testify a customized modal dialog. The arguments specify (in order) the parent component, message, title, selection blazon, message type, icon, options, and initial value for the dialog. Meet Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.
static int showConfirmDialog(Component, Object)
static int showConfirmDialog(Component, Object, String, int)
static int showConfirmDialog(Component, Object, Cord, int, int)
static int showConfirmDialog(Component, Object, String, int, int, Icon)
Show a modal dialog that asks the user a question. The arguments specify (in order) the parent component, message, championship, selection type, message type, and icon for the dialog. Encounter Creating and Showing Simple Dialogs for a give-and-take of the arguments and their effects.
static String showInputDialog(Object)
static String showInputDialog(Component, Object)
static Cord showInputDialog(Component, Object, String, int)
static String showInputDialog(Component, Object, String, int, Icon, Object[], Object)
Show a modal dialog that prompts the user for input. The single-argument version specifies but the bulletin, with the parent component assumed to be zero. The arguments for the other versions specify (in social club) the parent component, message, championship, message type, icon, options, and initial value for the dialog. See Creating and Showing Simple Dialogs for a discussion of the arguments and their effects.
static void showInternalMessageDialog(...)
static void showInternalOptionDialog(...)
static void showInternalConfirmDialog(...)
static String showInternalInputDialog(...)
Implement a standard dialog equally an internal frame. See the JOptionPane API documentation for the exact listing of arguments.
Methods for Using JOptionPanedue south Straight
Method or Constructor Purpose
JOptionPane()
JOptionPane(Object)
JOptionPane(Object, int)
JOptionPane(Object, int, int)
JOptionPane(Object, int, int, Icon)
JOptionPane(Object, int, int, Icon, Object[])
JOptionPane(Object, int, int, Icon, Object[], Object)
Creates a JOptionPane instance. Come across Creating and Showing Unproblematic Dialogs for a discussion of the arguments and their furnishings.
static Frame getFrameForComponent(Component)
static JDesktopPane getDesktopPaneForComponent(Component)
Handy JOptionPane class methods that discover the frame or desktop pane, respectively, that the specified component is in.
int getMaxCharactersPerLineCount() Determines where line breaks volition be automatically inserted in the option pane text. (The default is Integer.MAX_VALUE.) To utilize this method, you must create a JOptionPane subclass. For example, the post-obit code results in an option pane with i discussion per line, due to the fact that each word in the string is 5 characters or less:
JOptionPane op = new JOptionPane("This is the text.") {     public int getMaxCharactersPerLineCount() {         return 5;     } };                  
Oft Used JDialog Constructors and Methods
Method or Constructor Purpose
JDialog()
JDialog(Dialog)
JDialog(Dialog, boolean)
JDialog(Dialog, String)
JDialog(Dialog, String, boolean)
JDialog(Dialog, String, boolean, GraphicsConfiguration)
JDialog(Frame)
JDialog(Frame, boolean)
JDialog(Frame, String)
JDialog(Frame, String, boolean)
JDialog(Frame, String, boolean, GraphicsConfiguration)
JDialog(Window possessor)
JDialog(Window owner, Dialog.ModalityType modalityType)
JDialog(Window owner, String title)
JDialog(Window possessor, String title, Dialog.ModalityType modalityType)
JDialog(Window owner, Cord title, Dialog.ModalityType modalityType, GraphicsConfiguration gc)
Creates a JDialog instance. The Frame argument, if any, is the frame (usually a JFrame object) that the dialog depends on. Make the boolean argument true to specify a modal dialog, false or absent to specify a not-modal dialog. You tin can also specify the title of the dialog, using a string argument.
void setContentPane(Container)
Container getContentPane()
Become and set the content pane, which is usually the container of all the dialog'southward components. Come across Using Summit-Level Containers for more data.
void setDefaultCloseOperation(int)
int getDefaultCloseOperation()
Become and set up what happens when the user tries to close the dialog. Possible values: DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE (the default). Meet Responding to Window-Closing Events for more data.
void setLocationRelativeTo(Component) Centers the dialog over the specified component.
static void setDefaultLookAndFeelDecorated(boolean)
static boolean isDefaultLookAndFeelDecorated()
Set or get a hint equally to whether the dialog's window decorations (such as borders, or widgets to shut the window) should be provided past the current look and feel. Otherwise the dialog's decorations will be provided past the current window manager. Encounter Specifying Window Decorations for more data.

Examples that Use Dialogs

This table lists examples that apply JOptionPane or JDialog. To find other examples that use dialogs, see the example lists for progress confined, colour choosers, and file choosers.

Example Where Described Notes
DialogDemo,
CustomDialog
This section Creates many kinds of dialogs, using JOptionPane and JDialog.
Framework Brings up a confirmation dialog when the user selects the Quit menu detail.
ListDialog How to Employ BoxLayout Implements a modal dialog containing a scrolling list and ii buttons. Does not apply JOptionPane, except for the utility method getFrameForComponent.

alexanderellow1964.blogspot.com

Source: https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html

0 Response to "Java Open a Dialog Again Until Condition Is Met"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel