Javascript required
Skip to content Skip to sidebar Skip to footer

Gui With Popup Login/signup Popup Before a Program Java Updated FREE

Gui With Popup Login/signup Popup Before a Program Java

A Dialog window is an independent sub window meant to behave temporary notice apart from the main Swing Application Window. Most Dialogs present an mistake message or alert to a user, but Dialogs tin can nowadays images, directory trees, or only virtually anything uniform with the main Swing Application that manages them.

For convenience, several Swing component classes can directly instantiate and brandish dialogs. To create uncomplicated, standard dialogs, you use the JOptionPane class. The ProgressMonitor class tin put up a dialog that shows the progress of an operation. 2 other classes, JColorChooser and JFileChooser, also supply standard dialogs. To bring up a impress dialog, yous tin apply the Printing API. To create a custom dialog, use the JDialog form directly.

The code for uncomplicated dialogs tin can be minimal. For instance, hither is an informational dialog:

An informational dialog requires minimal code

Here is the code that creates and shows it:

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

The rest of this section covers the following topics:

  • An Overview of Dialogs
  • The DialogDemo Instance
  • JOptionPane Features
  • Creating and Showing Uncomplicated Dialogs
  • Customizing Button Text
  • Getting the User's Input from a Dialog
  • Stopping Automatic Dialog Closing
  • The Dialog API
  • Examples that Apply Dialogs

An Overview of Dialogs

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

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

Starting with JDK 7, you lot can modify dialog window modality behavior using the new Modality API. See The New Modality API for details.

The JDialog class is a subclass of the AWT coffee.awt.Dialog class. It adds a root pane container and support for a default close operation to the Dialog object . These are the same features that JFrame has, and using JDialog directly is very similar to using JFrame. If you're going to use JDialog straight, and so you lot should understand the textile in Using Superlative-Level Containers and How to Make Frames, especially Responding to Window-Closing Events.

Even when you lot use JOptionPane to implement a dialog, you're still using a JDialog behind the scenes. The reason is that JOptionPane is simply a container that can automatically create a JDialog and add itself to the JDialog's content pane.

The DialogDemo Example

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

DialogDemo lets you bring up many kinds of dialogs

Try this::

  1. Click the Launch button to run the Dialog Demo using Coffee™ Web Start (download JDK seven or later on). Alternatively, to compile and run the example yourself, consult the example alphabetize.Launches the DialogDemo example
  2. Click the Show it! button.
    A modal dialog will appear. Until yous close it, the application will be unresponsive, although it volition repaint itself if necessary. You can shut the dialog either by clicking a button 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 so the Prove information technology! 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 non-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 tin can quickly create and customize several different kinds of dialogs. JOptionPane provides support for laying out standard dialogs, providing icons, specifying the dialog title and text, and customizing the push button text. Other features allow you to customize the components the dialog displays and specify where the dialog should appear onscreen. You can even specify that an option pane put itself into an internal frame (JInternalFrame) instead of a JDialog.

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

JOptionPane'southward icon support lets yous easily specify which icon the dialog displays. You can use a custom icon, no icon at all, or any 1 of iv standard JOptionPane icons (question, data, warning, and error). Each expect and feel has its own versions of the iv standard icons. The following figure shows the icons used in the Java (and Windows) look and experience.

Icons used by JOptionPane
Icon clarification Java await and experience Windows look and feel
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
error The Java look and feel icon for error dialogs The Windows look and feel icon for error dialogs

Creating and Showing Simple Dialogs

For most elementary modal dialogs, you create and testify the dialog using one of JOptionPane's showThirtyDialog methods. If your dialog should exist an internal frame, then add Internal after show — for example, showMessageDialog changes to showInternalMessageDialog. If yous need to control the dialog window-endmost behavior or if you do not want the dialog to be modal, and then you should directly instantiate JOptionPane and add together information technology to a JDialog instance. Then invoke setVisible(true) on the JDialog to make it appear.

The 2 well-nigh useful proveXxxDialog methods are showMessageDialog and showOptionDialog. The showMessageDialog method displays a simple, 1-button dialog. The showOptionDialog method displays a customized dialog — it can display a variety of buttons with customized button text, and tin can incorporate a standard text message or a collection of components.

The other 2 showXxxDialog methods are used less often. The showConfirmDialog method asks the user to confirm something, just presents standard button text (Yes/No or the localized equivalent, for case) rather than button text customized to the user state of affairs (First/Abolish, for example). A fourth method, showInputDialog, is designed to display a modal dialog that gets a cord from the user, using either a text field, an uneditable combo box or a list.

Hither are some examples, taken from DialogDemo.java, of using showMessageDialog, showOptionDialog, and the JOptionPane constructor. For more case code, come across DialogDemo.java and the other programs listed in Examples that Use Dialogs.

showMessageDialog
Displays a modal dialog with one push button, which is labeled "OK" (or the localized equivalent). You 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 non supposed to exist green.");                      
Informational dialog with custom title, warning icon
//custom title, warning icon JOptionPane.showMessageDialog(frame,     "Eggs are non supposed to exist dark-green.",     "Inane warning",     JOptionPane.WARNING_MESSAGE);                      
Informational dialog with custom title, error icon
//custom championship, fault icon JOptionPane.showMessageDialog(frame,     "Eggs are not supposed to exist green.",     "Inane error",     JOptionPane.ERROR_MESSAGE);                      
Informational dialog with custom title, no icon
//custom title, no icon JOptionPane.showMessageDialog(frame,     "Eggs are non supposed to be green.",     "A evidently message",     JOptionPane.PLAIN_MESSAGE);                      
Informational dialog with custom title, custom icon
//custom championship, custom icon JOptionPane.showMessageDialog(frame,     "Eggs are not supposed to exist 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 tin change the text that appears on the buttons of standard dialogs. You can also perform many other kinds of customization.
Yes/No/Cancel (in different words); showOptionDialog
//Custom button text Object[] options = {"Yes, please",                     "No, thank you",                     "No eggs, no ham!"}; int n = JOptionPane.showOptionDialog(frame,     "Would you similar some dark-green eggs to go "     + "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, message, title, and then on. You must then add the option pane to a JDialog, register a holding-change listener on the option pane, and show the dialog. Run into Stopping Automatic Dialog Endmost for details.
Explicitly used the JOptionPane constructor
final JOptionPane optionPane = new JOptionPane(     "The only way to close this dialog is by\north"     + "pressing one of the post-obit buttons.\due north"     + "Exercise you understand?",     JOptionPane.QUESTION_MESSAGE,     JOptionPane.YES_NO_OPTION);                      

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

Component parentComponent
The first argument to each showXxxDialog method is ever the parent component, which must be a Frame, a component within a Frame, or nil. If you specify a Frame or Dialog, then the Dialog will appear over the eye of the Frame and follow the focus behavior of that Frame. If you specify a component inside a Frame, then the Dialog will appear over the middle of that component and will follow the focus behavior of that component'south Frame. If you specify null, then the look and feel will pick an advisable position for the dialog — by and large the centre of the screen — and the Dialog will non necessarily follow the focus behavior of any visible Frame or Dialog.

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

Object message
This required argument specifies what the dialog should display in its main area. Generally, you lot specify a cord, which results in the dialog displaying a label with the specified text. Y'all tin split up the message over several lines by putting newline (\n) characters within the message cord. For example:
"Complete the sentence:\n \"Green eggs and...\""              
String title
The title of the dialog.
int optionType
Specifies the set of buttons that appear at the bottom of the dialog. Cull from one of the following 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 ane of the following values: PLAIN_MESSAGE (no icon), ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE.
Icon icon
The icon to brandish in the dialog.
Object[] options
Generally used to specify the cord displayed by each button at the bottom of the dialog. Encounter Customizing Button Text in a Standard Dialog for more data. Can also be used to specify icons to be displayed by the buttons or non-push components to be added to the push row.
Object initialValue
Specifies the default value to exist selected.

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

Customizing Button Text

When you use JOptionPane to create a dialog, yous can either utilize the standard push text (which might vary by expect and feel and locale) or specify different text. Past default, the option pane type determines how many buttons appear. For example, YES_NO_OPTION dialogs accept two buttons, and YES_NO_CANCEL_OPTION dialogs have iii buttons.

The post-obit code, taken from DialogDemo.coffee, creates two Yes/No dialogs. The outset dialog is implemented with showConfirmDialog, which uses the look-and-experience wording for the two buttons. The second dialog uses showOptionDialog and so information technology can customize the wording. With the exception of wording changes, the dialogs are identical.

A yes/no dialog, in those words [but perhaps translated]
//default icon, custom title int n = JOptionPane.showConfirmDialog(     frame,     "Would you like 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 northward = JOptionPane.showOptionDialog(frame,     "Would you similar dark-green eggs and ham?",     "A Dizzy Question",     JOptionPane.YES_NO_OPTION,     JOptionPane.QUESTION_MESSAGE,     zero,     //do not utilise a custom Icon     options,  //the titles of buttons     options[0]); //default push title                  

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

Even if you change the strings that the standard dialog buttons brandish, the return value is still one of the pre-defined 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 not return an integer is showInputDialog, which returns an Object instead. This Object is mostly a Cord reflecting the user's choice. Hither is an example of using showInputDialog to create a dialog that lets the user choose one of iii strings:

An input dialog with a combo box
Object[] possibilities = {"ham", "spam", "yam"}; String southward = (String)JOptionPane.showInputDialog(                     frame,                     "Complete the judgement:\n"                     + "\"Green eggs and...\"",                     "Customized Dialog",                     JOptionPane.PLAIN_MESSAGE,                     icon,                     possibilities,                     "ham");  //If a cord was returned, say so. if ((s != nada) && (s.length() > 0)) {     setLabel("Dark-green eggs and... " + southward + "!");     return; }  //If y'all're hither, the return value was zip/empty. setLabel("Come on, terminate the sentence!");          

If you practice non intendance to limit the user'due south choices, you tin either use a form of the showInputDialog method that takes fewer arguments or specify nothing for the array of objects. In the Coffee look and feel, substituting nothing for possibilities results in a dialog that has a text field and looks like this:

An input dialog with a text field

Because the user can type anything into the text field, yous might want to check the returned value and ask the user to try again if it is invalid. Another arroyo is to create a custom dialog that validates the user-entered information before it returns. See CustomDialog.java for an instance of validating data.

If yous're designing a custom dialog, you need to design your dialog's API and then that you can query the dialog about what the user chose. For case, CustomDialog has a getValidatedText method that returns the text the user entered.

Stopping Automatic Dialog Closing

By default, when the user clicks a JOptionPane-created push button, the dialog closes. But what if you lot desire to bank check the user's respond earlier closing the dialog? In this example, y'all must implement your own belongings change listener then that when the user clicks a button, the dialog does not automatically close.

DialogDemo contains two dialogs that implement a belongings change listener. One of these dialogs is a custom modal dialog, implemented in CustomDialog, that uses JOptionPane both to get the standard icon and to get layout assistance. The other dialog, whose code is below, uses a standard Yep/No JOptionPane. Though this dialog is rather useless as written, its code is elementary enough that y'all can utilise information technology as a template for more complex dialogs.

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

final JOptionPane optionPane = new JOptionPane(                 "The only way to close this dialog is by\north"                 + "pressing ane of the post-obit buttons.\n"                 + "Practice yous understand?",                 JOptionPane.QUESTION_MESSAGE,                 JOptionPane.YES_NO_OPTION);  final JDialog dialog = new JDialog(frame,                               "Click a button",                              true); dialog.setContentPane(optionPane);            dialog.setDefaultCloseOperation(     JDialog.DO_NOTHING_ON_CLOSE); dialog.addWindowListener(new WindowAdapter() {     public void windowClosing(WindowEvent we) {         setLabel("Thwarted user try to close window.");     } });            optionPane.addPropertyChangeListener(     new PropertyChangeListener() {         public void propertyChange(PropertyChangeEvent e) {             String prop = east.getPropertyName();              if (dialog.isVisible()               && (e.getSource() == optionPane)              && (prop.equals(JOptionPane.VALUE_PROPERTY))) {                 //If you were going to cheque something                 //before endmost the window, you'd practice                 //it here.                 dialog.setVisible(false);             }         }     }); dialog.pack(); dialog.setVisible(truthful);  int value = ((Integer)optionPane.getValue()).intValue(); if (value == JOptionPane.YES_OPTION) {     setLabel("Proficient."); } else if (value == JOptionPane.NO_OPTION) {     setLabel("Try using the window decorations "              + "to close the not-motorcar-closing dialog. "              + "You can't!"); }          

The Dialog API

The following tables list the commonly used JOptionPane and JDialog constructors and methods. Other methods y'all're likely to phone call are divers by the Dialog, Window and Component classes and include pack, setSize, and setVisible.

The API is listed equally follows:

  • Showing Standard Modal Dialogs (using JOptionPane Course Methods)
  • Methods for Using JOptionPanesouth Straight
  • Frequently Used JDialog Constructors and Methods
Showing Standard Modal Dialogs (Using JOptionPane Class Methods)
Method Purpose
static void showMessageDialog(Component, Object)
static void showMessageDialog(Component, Object, String, int)
static void showMessageDialog(Component, Object, String, int, Icon)
Show a i-button, modal dialog that gives the user some information. The arguments specify (in society) the parent component, message, title, bulletin type, and icon for the dialog. Meet Creating and Showing Simple Dialogs for a discussion of the arguments and their furnishings.
static int showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object) Show a customized modal dialog. The arguments specify (in society) the parent component, bulletin, title, option type, message blazon, icon, options, and initial value for the dialog. Come across Creating and Showing Simple Dialogs for a word of the arguments and their effects.
static int showConfirmDialog(Component, Object)
static int showConfirmDialog(Component, Object, Cord, int)
static int showConfirmDialog(Component, Object, String, int, int)
static int showConfirmDialog(Component, Object, String, int, int, Icon)
Bear witness a modal dialog that asks the user a question. The arguments specify (in order) the parent component, bulletin, championship, option blazon, message type, and icon for the dialog. Meet Creating and Showing Simple Dialogs for a give-and-take of the arguments and their effects.
static Cord showInputDialog(Object)
static String showInputDialog(Component, Object)
static String showInputDialog(Component, Object, Cord, int)
static String showInputDialog(Component, Object, Cord, int, Icon, Object[], Object)
Show a modal dialog that prompts the user for input. The single-argument version specifies only the bulletin, with the parent component assumed to be null. The arguments for the other versions specify (in order) the parent component, message, championship, message type, icon, options, and initial value for the dialog. See Creating and Showing Unproblematic Dialogs for a word of the arguments and their effects.
static void showInternalMessageDialog(...)
static void showInternalOptionDialog(...)
static void showInternalConfirmDialog(...)
static String showInternalInputDialog(...)
Implement a standard dialog as an internal frame. Run across the JOptionPane API documentation for the exact list of arguments.
Methods for Using JOptionPanes 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. See Creating and Showing Elementary Dialogs for a discussion of the arguments and their effects.
static Frame getFrameForComponent(Component)
static JDesktopPane getDesktopPaneForComponent(Component)
Handy JOptionPane form methods that observe the frame or desktop pane, respectively, that the specified component is in.
int getMaxCharactersPerLineCount() Determines where line breaks volition exist automatically inserted in the option pane text. (The default is Integer.MAX_VALUE.) To apply this method, y'all must create a JOptionPane bracket. For case, the following code results in an selection pane with one give-and-take 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;     } };                  
Frequently 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 owner)
JDialog(Window owner, Dialog.ModalityType modalityType)
JDialog(Window possessor, String title)
JDialog(Window possessor, String title, Dialog.ModalityType modalityType)
JDialog(Window owner, String championship, Dialog.ModalityType modalityType, GraphicsConfiguration gc)
Creates a JDialog example. The Frame argument, if whatever, is the frame (unremarkably a JFrame object) that the dialog depends on. Brand the boolean argument true to specify a modal dialog, false or absent-minded to specify a not-modal dialog. Y'all can also specify the championship of the dialog, using a string argument.
void setContentPane(Container)
Container getContentPane()
Get and set the content pane, which is usually the container of all the dialog's components. See Using Pinnacle-Level Containers for more information.
void setDefaultCloseOperation(int)
int getDefaultCloseOperation()
Get and set what happens when the user tries to close the dialog. Possible values: DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE (the default). See Responding to Window-Closing Events for more than data.
void setLocationRelativeTo(Component) Centers the dialog over the specified component.
static void setDefaultLookAndFeelDecorated(boolean)
static boolean isDefaultLookAndFeelDecorated()
Set up or get a hint as to whether the dialog's window decorations (such as borders, or widgets to close the window) should be provided by the electric current wait and feel. Otherwise the dialog'due south decorations will be provided past the current window director. See Specifying Window Decorations for more data.

Examples that Use Dialogs

This table lists examples that use JOptionPane or JDialog. To find other examples that utilise dialogs, come across the example lists for progress confined, color choosers, and file choosers.

Case Where Described Notes
DialogDemo,
CustomDialog
This section Creates many kinds of dialogs, using JOptionPane and JDialog.
Framework Brings upward a confirmation dialog when the user selects the Quit menu item.
ListDialog How to Use BoxLayout Implements a modal dialog containing a scrolling list and two buttons. Does non apply JOptionPane, except for the utility method getFrameForComponent.

Gui With Popup Login/signup Popup Before a Program Java

DOWNLOAD HERE

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

Posted by: newberryventrout.blogspot.com