Using JOptionPane (InputDialog)

Guest Posts Steven



In this article we'll see how to use InputDialog from JOptionPane. With this option we can get the input from the user and use that in our program.

For this example we're using the same constructor we used with the MassageDialog. We're going to get the user name and display it on our screen.

Here's the code:

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class exampleJFrame extends JFrame{

   private JPanel _panel;

   /*
   * buttons are global variables
   */
   private JButton _clickme;

   /**
   * Create the frame.
   */
   public exampleJFrame() {
      setVisible(true); //we make the window visible
      setResizable(false); // if write false, you won't be able to resize the window
      setTitle("Example"); //you set the title for the window
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null); // you make the window appear at the center of the screen
      setSize(294,159); // you set the size of the window
      _panel = new JPanel();
      getContentPane().add(_panel);
      _panel.setLayout(null); // you set the Layout to null = Absolute Layout

      final JLabel lblYoureNameIs = new JLabel("You're name is: ");
      lblYoureNameIs.setBounds(39, 24, 181, 14);
      _panel.add(lblYoureNameIs);

      _clickme = new JButton("Click Me!");
      _clickme.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {
         // we save the name in variable
         String name=JOptionPane.showInputDialog(null, "Enter your name", "Name", JOptionPane.PLAIN_MESSAGE);
                                           //   parent    message          title      message type
         if(name==null)name=""; // we check if the user didn't write anything or if he clicks cancel
         lblYoureNameIs.setText("You're name is: "+name);// we change the label
     }
   });
   _clickme.setBounds(98, 55, 89, 23); // you set the size and position of the button in the JPanel
   _panel.add(_clickme); // you add the button to the panel

  }
   public static void main(String[] args) {
     exampleJFrame example=new exampleJFrame();
  }
}



The result would be:

You click the Button:

frame1

You enter your name:

frame2

Click Accept:

frame3

That's it for this time. You can try to use the different options you have with JOptionPane.