JOptionPane tutorial

JOptionPane Introduction

JOptionPane is a basic component defined in Java swing, it makes easy to pop a standard dialog box that accept user input or prompts user for a value, JOptionPane contains classes used for a graphical user interface (GUI) Facilitates data entry and data output.

How Do I use Joptionpane – tutorial and example

JOptionPane has four static methods showXxxDialog, which are used to prompt different dialog, we can directly call these methods to display dialog to users.

1. showConfirmDialog:

Show a confirm message dialog that accepts a option, Generally user have three options: yes, no or cancel. This is the example code:

int returnType = JOptionPane.showConfirmDialog(null, "Choose any button");

2. showInputDialog:

Show a input message dialog that user can input a message and click OK or Cancel. This is example code tutorial:

String userInput = JOptionPane.showInputDialog("Please input any value to continue");

3. showMessageDialog:

Show a message dialog that user only can see the message and then click button. This is example code tutorial:

JOptionPane.showMessageDialog(null, "Choose any button");

4. showOptionDialog:

The Grand Unification of the above three

Notice: all prompted dialogs are modal, which means it blocks input to some other top-level windows in the application, and all showXxxDialog methods block the current thread until the user’s interaction is complete.

We introduced above that use static method to bring dialog up, another way is also available which instantiates JOptionPane by using a constructor and then call createDialog() or createInternalFrame() to paint it.

One whole tutorial/example for JOptionPane

public static void main(String[] args) {
    JFrame frame = new JFrame("Test Frame");
    frame.setSize(new Dimension(200, 200));
    JButton button = new JButton("Submit");
    button.setSize(new Dimension(100, 60));
    button.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
          String title = "Are you want to quit this window?";
          if (JOptionPane.showConfirmDialog(null, title) == JOptionPane.YES_OPTION) {
             System.exit(0);
          }
       }
    });
    frame.add(button, BorderLayout.CENTER);
    frame.setVisible(true);
}
You may refer to more JOptionPane tutorial/example from http://java.sun.com/javase/6/docs/api/javax/swing/JOptionPane.html

Оцените статью
ASJAVA.COM
Добавить комментарий

Your email address will not be published. Required fields are marked *

*

code