Can we read from JOptionPane by requesting input from user in Java?


Yes, we can read from JOptionPane. Here, we will get the result of the showInputDialog() in a String variable −

String input = JOptionPane.showInputDialog("Enter the C++ lessons you covered till now?");

After getting the result, we will convert it to integer with parseInt() and display it on Console −

int res = Integer.parseInt(input);
System.out.println("Lessons covered = "+res);

The following is an example to read from JOptionPane by requesting input from user −

Example

package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      ImageIcon icon = new ImageIcon(new URL("http −//www.tutorialspoint.com/images/C-PLUS.png"));
      JLabel label = new JLabel(icon);
      JPanel panel = new JPanel(new GridBagLayout());
      panel.add(label);
      panel.setOpaque(true);
      panel.setBackground(Color.ORANGE);
      JPanel textPanel = new JPanel(new GridLayout(10, 5));
      for (int i = 0; i < 20; i++) {
         textPanel.add(new JLabel("Learn C++"));
      }
      JPanel panel2 = new JPanel(new BorderLayout());
      panel2.add(textPanel);
      panel2.add(panel, BorderLayout.EAST);
      JOptionPane.showMessageDialog(null, panel2, "Course",JOptionPane.DEFAULT_OPTION);
      String input = JOptionPane
      .showInputDialog("Enter the C++ lessons you covered till now?");
      int res = Integer.parseInt(input);
      System.out.println("Lessons covered = "+res);
   }
}

Output

On clicking OK above, input would be requested from the user as shown below −

Now, on pressing ENTER the lesson numbers added above would get displayed in the Console as shown below −

Updated on: 30-Jul-2019

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements