Java: getting user inputs

The Java program below provided examples of getting user inputs by Scanner and JOptionPane as well as getting password by using JOptionPane.

import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;

public class GetInputs {
    
	//Get user input from Scanner
    public static void getInputsFromScanner()
    {        
        String name;
        Scanner input = new Scanner(System.in);
        System.out.print("Enter your name > ");
        name = input.nextLine();
        System.out.print("You entered your name as: ");
        System.out.println(name);
        
    }
    
    //Get user input from JOptionPane
    public static void getInputsFromJOptionPane()
    {
        String name;
        name = JOptionPane.showInputDialog(null,
         "Please enter your name");
        JOptionPane.showMessageDialog(null,"Hi "+ name);
        
    }
    
    //Get user password from JOptionPane
    public static String getPassCodeInput()
    {
    	JPanel panel = new JPanel();
    	JLabel label = new JLabel("Enter a password:");
    	JPasswordField pass = new JPasswordField(10);
    	panel.add(label);
    	panel.add(pass);
    	String[] options = new String[]{"OK", "Cancel"};
    	int option = JOptionPane.showOptionDialog(null, panel, "Password Verification",
    	                         JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE,
    	                         null, options, null);
    	if(option == 0) // pressing OK button
    	{
    	    return new String(pass.getPassword());
    	}
        return null;
    }
    
    public static void main(String args[])
    {
       getInputsFromScanner();
       getInputsFromJOptionPane();
       System.out.println("you entered: "+getPassCodeInput());
    }
    
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search