Search code examples
javaswingnullpointerexceptionjoptionpane

About JOptionPane CANCEL_OPTION


I could not imply the cancel option to method twice. (Both first input dialog box and second input dialog box for football) When I click cancel button, NullPointerException error occurs. Any idea?

public void RandomDistribution() {

    String[] gametypes = {"NBA", "Euroleague", "NCAA", "NHL", "Football" };
    String question = "Choose the Game";
    String title = "Memory Game";
    ImageIcon entry = new ImageIcon(getClass().getResource("background.jpg"));
    String c = (String) JOptionPane.showInputDialog(null, question, title,
            JOptionPane.PLAIN_MESSAGE, entry, gametypes,gametypes[4]);

    if (c.equals("Football")) {
        String[] f_level = {"Easy", "Normal", "Hard"};
        String question_f = "Choose the Level";
        String title_f = "Memory Game - Football";
        String c2 = (String) JOptionPane.showInputDialog(null, question_f, title_f,
                JOptionPane.PLAIN_MESSAGE, null, f_level,f_level[2]);
        if (c2.equals("Easy")) {
            c = "Football1";
        } else if (c2.equals("Normal")) {
            c = "Football2";
        } else if (c2.equals("Hard")){
            c = "Football3";
        }
    }

    for (int i = 0; i < 64; i++) {
        PicOfCells[i] = (int) (Math.random() * 64) + 1;
        for (int j = 0; j < i; j++) {
            if (PicOfCells[i] == PicOfCells[j] && i != j && i != 0) {
                --i;
            }
        }
    }

    for (int i = 0; i < 64; i++) {
        PicOfCells[i] = (PicOfCells[i] % 32);
        PicOfAllCells[i] = new ImageIcon(getClass().getResource(PicOfCells[i] + 1 + c +".gif"));
    }
    StartGame.doClick();
}

Solution

  • If I understand you correctly, your problem is that you are getting a NullPointerException when you cancel one of the two dialogs.

    Taking a look at the documentation of JOptionPane.showInputDialog(…) explains what will be returned when the user cancels the input:

    Returns: user's input, or null meaning the user canceled the input

    So your code

    String c = (String) JOptionPane.showInputDialog(null, question, title,
            JOptionPane.PLAIN_MESSAGE, entry, gametypes,gametypes[4]);
    

    sets c to null when the user cancels the input. Because you do

    if (c.equals("Football")) {
    

    in the next line, you are trying to call the method equals(…) on a null reference, which is not possible and causes the NullPointerException you get. To prevent the exception from being thrown you need to check c for null, e.g. like so:

    if (c == null) {
        // do whatever you want to do when the user canceled input
    } else if (c.equals("Football")) {
    

    Of course the same goes for c2… ;-)