I'm learning Swing with Java and I've very early on run into an issue with getting my components to show in the window. If I use the following code:
import javax.swing.*;
public class win extends JFrame {
public static void main(String[] args) {
new win();
}
public win(){
this.setTitle("WIN");
this.setSize(200,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel l = new JLabel("Label");
this.add(l);
this.setVisible(true);
}
}
my label will not show unless I resize the window. I searched other questions and some suggested that the lack of pack, revalidate, validate and or repaint methods were the culprit. If I add pack to the same code:
import javax.swing.*;
public class win extends JFrame {
public static void main(String[] args) {
new win();
}
public win(){
this.setTitle("WIN");
this.setSize(200,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel l = new JLabel("Label");
this.add(l);
this.pack();
this.setVisible(true);
}
}
My window takes about 10 seconds to display
UPDATE:
Adding my code to the EDT as suggested by Frakcool did not work.
This code also renders after a 10 second delay. I don't think it is a problem with my computer being slow, it is a quad core 32 gb ram machine running High Sierra. Currently I'm running these programs on Java 8.
USING EDT:
Everyone suggest that not using the EDT is the culprit, however I've tried it and it does not seem to be the issue. Unless there is something wrong with this code, the EDT is not the solution:
import javax.swing.*;
public class Window extends JFrame {
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Window();
}
});
}
public Window(){
this.setTitle("WINDOW");
JLabel l = new JLabel("Label");
this.add(l);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
I'm still getting a 10 second startup just for this one Label, and it is the same with other swing components.
UPDATE:
The issue is definitely not anything in the code (with or without EDT), as I'm able to run this code without delay on both another OSX system (Mojave) and on Ubuntu via Virtualbox on the problem machine (High Sierra). The issue must be with either High Sierra or some settings I have on my personal system or on the JVM