I have 2 classes, a MainClass
and a AdminPage
. The AdminPage
only consists of a JLabel
with the text AdminPage
. I use the Nimbus Look & Feel
.
If I create a new AdminPage
and put it into the MainClass
it looks like this:
AdminPage adminPage = new AdminPage();
But if I change the modifier of the AdminPage
to static
, the font becomes bold and the background changes:
static AdminPage adminPage = new AdminPage();
I really dont understand why this is happening. It's causing me no problems, but a lot of confusion. I suppose this has something to do with how the UIManager
sets the Look and Feel, but I cant pinpoint the exact cause.
Explanations would be appreciated!
Here is my mcve-Code:
MainClass.java:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import net.miginfocom.swing.MigLayout;
public class MainClass extends JFrame {
private static final long serialVersionUID = 1L;
JPanel centerPanel = new JPanel();
AdminPage adminPage = new AdminPage();
public MainClass() {
setBounds(300, 50, 300, 300);
setLayout(new MigLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
centerPanel.setLayout(new MigLayout());
centerPanel.add(adminPage);
add(centerPanel, "growx, wrap");
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
MainClass window = new MainClass();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
AdminPage.java:
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class AdminPage extends JPanel {
private static final long serialVersionUID = 1L;
JPanel contentPanel = new JPanel();
JLabel testLabel = new JLabel("Adminpage");
public AdminPage() {
setLayout(new MigLayout());
contentPanel.setLayout(new MigLayout());
contentPanel.add(testLabel);
add(contentPanel);
}
}
EDIT:
Thanks to a comment from Henning Luther I've tried to initialize the UIManager
in a static way:
static {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}
catch (Exception ex) {
}
}
But my class still does not use the intended L&F.
You set the Look&Feel after the AdminPage is instantiated, that's why is not applied to it. The Look&Feel is not changed for all existing UI instances when setting in the UIManager. Since you set AdminPage to static its instantiated on class loading and before main is executed.