Search code examples
javajoptionpanejdialog

Why are my JOptionPane message dialogs popping up behind the console window?


I'm making a somewhat simple text game for my cs course. The majority of the game is played out in the console window, however, at a certain if the user wins or loses the game, a JOptionPane message dialog window shows up and says that the user has won or lost

My problem is that the JOptionPane is showing up on the layer the furthest back of all my other windows and applications open. In all my other programs like this, it has always appeared in the front.

I've found a temporary fix for this however I was wondering if anyone could give me a definitive reason as to why this may be happening to avoid the problem in the future


Solution

  • I'm not exactly sure why exactly this happens but for anyone who finds this in the future, this is why I was having this problem.

    In my program, I had certain sections that used input from the console window (so scanners) and then displayed JOptionPanes based off of certain requirements of the game (i.e winning losing, etc).

    For whatever reason, whenever you are taking user input from the scanner class then opening a JOptionPane, the JOptionPane will always open in the furthest section back from all your open tabs which is what was happening to me.

    As a workaround for this bug, I did the following:

    1. Declare a JDialog and setAlwaysOnTop to true:

      final JDialog dialog = new JDialog();
      dialog.setAlwaysOnTop(true);
      
    2. Every time I made a JOptionPane open, instead of writing null as the first parameter I put the name of the JDialog so it looked something like this:

      final JDialog dialog = new JDialog();
      dialog.setAlwaysOnTop(true);
      JOptionPane.showMessageDialog(dialog, "You win!);
      

    With this, my JOptionPanes always popped up in front of the console even when using the scanner class.