Search code examples
javajoptionpane

Java- Reading input and output on JOptionPane


I'm struggling on my code, it works good with the code that I commented but it doesn't work when I use JOptionPane.showOptionDialog , I am using Option dialog its because I want that code to display a skip or cancel button and I don't know how do I change the String of that button yet too, I would be really appreciate if someone can solve this problem for me.

import javax.swing.*;
import java.util.Scanner;

public class Login {
    public static void main(String[] args) {
        String userName;

        //This will ask user to input the username
        userName = JOptionPane.showInputDialog(null, "Please enter your name", "Welcome", JOptionPane.INFORMATION_MESSAGE);

        // JOptionPane.showMessageDialog   <<<This code replace the below one then it will work perfectly
        JOptionPane.showOptionDialog(null, "Welcome " + userName + "\n\nWould you like to have a tutorial about this game?", "Welcome", JOptionPane.OK_CANCEL_OPTION);
    }
}

Solution

  • Your problem is JOptionPane.showOptionDialog requires more arguments than you provided. If you check the documentation you'll see you have to also provide the messageType, an icon, the options and the default option, where the last 3 can be null, so your call has to be

    JOptionPane.showOptionDialog(
        null,
        "Welcome " + userName + "\n\nWould you like to have a tutorial about this game?",
        "Welcome",
        JOptionPane.OK_CANCEL_OPTION,
        JOptionPane.INFORMATION_MESSAGE,
        null,
        null,
        null
    );