Search code examples
javajava.util.scannerjoptionpane

Why is my JOptionPane not appearing when I use a Scanner?


I have narrowed down my problem: JOptionPane will not appear if I use a Scanner. For example, this works fine:

public static void main(String[] args) {
    System.out.println("Before the dialog.");
    JOptionPane.showMessageDialog(null, "Please.");
    System.out.println("After the dialog.");
}

Even this works, too:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Before the dialog.");
    JOptionPane.showMessageDialog(null, "Please.");
    System.out.println("After the dialog.");
}

But, this does not work:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int hi = butler.nextInt();
    System.out.println("Before the dialog.");
    JOptionPane.showMessageDialog(null, "Please.");
    System.out.println("After the dialog.");
}

In the last example, the program waits for input, then it displays "Before the dialog." After that, the program seems to freeze.

I tried closing the scanner before the creating the dialog, but that had no effect.


Solution

  • It does appear after the input is read by the Scanner. It's just not appearing as the top level window. See JOptionPane won't show its dialog on top of other windows for how to solve this.