I have this class, let’s say, Foo. It extends JFrame and is a singleton. That being said, it has two static fields: 1) an instance of Foo and 2) a Color.
Here’s a code snippet of Foo:
public class Foo extends JFrame{
private static final Color FOO_RED = new Color(155, 64, 69);
private static final Foo INSTANCE = new Foo();
private Foo(){
//do stuff
}
public static Foo getInstance(){
return INSTANCE;
}
}
I also have another class, let’s say, Launcher. This is the main class that is responsible for launching the application. It’s a simple class in that its only job is to delegate the task of constructing Foo to the EDT.
Here’s a code snippet of Launcher:
public class Launcher{
public static void main(String[] args){
SwingUtilities.invokeLater((new Runnable(){
@Override
public void run()
{
Foo.getInstance();
}
}));
}
}
Now, this all works just fine. But, when I switch the ordering of Foo‘s fields (See below), the components that use FOO_RED are no longer painted this color.
public class Foo extends JFrame{
private static final Foo INSTANCE = new Foo(); //declared before Color
private static final Color FOO_RED = new Color(155, 64, 69);
private Foo(){
//do stuff
}
public static Foo getInstance(){
return INSTANCE;
}
}
So, this begs the question, does the ordering of static fields matter when it comes to Swing?
As already mentioned, ordering of static fields does matter. Executed in the order they appear.
I would make another change to this example. This would make you static field order less important.
UPDATE: Use IDOH (Initialization on Demand Holder) pattern to make singleton thread safe.