How to use dialog boxes: showMessageDialog and showInputDialog

In this tutorial we are going to learn how the dialog boxes work, taking a look at an example. We will first use the MessageDialog boxes which display information:

and afterwards the InputDialog boxes which ask for information which the program then keeps:

With the following code we are going to see how does these two types of dialog boxes work. First it creates two InputDialog which ask for a user and a password and then depending if the data is correct or not, the program shows us a MessageDialog with the result; "login ok" if it is correct and "login failed" if its not:

package com.edu4java.swing.tutrial1;

import javax.swing.JOptionPane;

public class Login {
	public static void main(String[] args) {
		String user = JOptionPane.showInputDialog(null, "user");
		String password = JOptionPane.showInputDialog(null, "password");

		if ("edu4java".equals(user) && "myPassword".equals(password)) {
			JOptionPane.showMessageDialog(null, "login ok");
		}else {
			JOptionPane.showMessageDialog(null, "login failed");
		}
	}
}
<< Index Next >>