-2

I have two classes, Game.java and GameOver.java.

Game.java
GameOver.java

This part of the code won't work when I launch the program:

try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Throwable e) {
        e.printStackTrace();
    }

The Look and Feel won't set the first time, although when the GameOver class is run and you press retry, the Look and Feel does set. I have tried to track down this issue, but I do not know what is causing it. What is wrong with my code and how do I fix it?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 3
    Code should be posted in the forum, not on another website. Also, in the future, post a proper [MCVE] that demonstrates the problem. Your question is about the LAF not working. So the code related to recreating the GUI is not relevant to the question. Simplify the problem when you post the code. So first get the code working with a few components, before you start testing your entire application. – camickr Oct 23 '18 at 01:02
  • 1
    `UIManager.setLookAndFeel("..WindowsLookAndFeel");` Don't hard code that `String`. The Windows PLAF will only be available on Windows (for which Linux and OS X users are generally grateful). Instead use `UIManager.getSystemLookAndFeelClassName()` .. – Andrew Thompson Oct 23 '18 at 05:08
  • @AndrewThompson Thanks! That was a good suggestion, although it didn't fix the problem. – AwesomeMaster Oct 23 '18 at 22:54
  • BTW, I'm using WindowBuilder, so that's why the string was hardcoded. – AwesomeMaster Oct 23 '18 at 23:51

2 Answers2

0

This part of the code won't work when I launch the program.

My guess is that the problem is because you don't execute the code on Event Dispatch Thread (EDT).

Part of your code is executing on a regular Thread and the part the creates the components is executing on the EDT. I would guess the LAF is not set when the GUI creation code is executed.

All GUI related code should be executed on the EDT.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • How am I able to fix this? I don't know where to change the code – AwesomeMaster Oct 23 '18 at 22:53
  • @AwesomeMaster The first statement in your class is setting the LAF. Your second statement is creating the Runnable object for your invokeLater(). The LAF should be added to the Runnable code. Read the Swing tutorial on [Concurrency](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for more information about the `EDT`. – camickr Oct 24 '18 at 03:01
  • Thanks! That fixed it! – AwesomeMaster Oct 28 '18 at 23:24
0

You're doing too much in the static initializers of one class. Have a class for the app (where you set the LAF) and another class for the JFrame that gets created and shown by the app class.

Matt Hovey
  • 85
  • 5