JOptionPane Example: It is easy to take input using Swing. showInputDialog() method of JOptionPane displays a dialog box in which the user can enter data. The method reads the data and returns the data as a string.
JOptionPane Example with user input of two numbers
import javax.swing.*;
public class InputDemo
{
public static void main(String args[])
{
String str1 = JOptionPane.showInputDialog("Enter First Number");
String str2 = JOptionPane.showInputDialog("Enter Second Number");
// input dialog returns always a string
double fn = Double.parseDouble(str1);
double sn = Double.parseDouble(str2);
JOptionPane.showMessageDialog( null, "The Product is " + fn*sn, "Product", JOptionPane.INFORMATION_MESSAGE);
}
}
Output screen on JOptionPane Example
String str1 = JOptionPane.showInputDialog(“Enter First Number”);
The return type of showInputDialog() method is a string. It is required to parse (using wrapper classes) into a double value.
The same JOptionPane can be used ti display messages to user like println() method does. Refer showMessageDialog() in Swing JOptionPane – Displaying Message.
Note: Always the second parameter in the message dialog must be a string.
Total 4 programs are given on JButton:
1. JButton with Images and Labels
2. JButton Border
3. JButton Label Style
4. JButton ActionListener