I am using Java 11 on Debian 4. I am trying to build a very basic Java GUI. To start with I have the following code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
public class BasicSwing extends JFrame {
JPanel p = new JPanel();
JButton b = new JButton("Hello");
public static void main (String[] args) {
new BasicSwing();
}
public BasicSwing() {
super("Basic Swing");
setSize(400,300);
setResizable(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
p.add(b);
add(p);
setVisible(true);
}
}
I have the X11 server running. The code does not fail but the GUI does not show up. I am not using Netbeans and I compile and run the code just as I would run and compile any other java code, ie with javac and java commands.The code does not stop and does not throw any error. Am I missing something very basic? I have seen a lot of discussion on the GUI not showing up but I am unable to find a solution to this problem given my specific development environment.
CodePudding user response:
Instead of calling the setVisible
method inside of your JFrame extended class's constructor, You should make a call on it in your main function.
Do it this way:
public static void main (String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BasicSwing mySwingApp = new BasicSwing();
mySwingApp.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Please read more about why I use a java.awt.EventQueue
here.
Update:
It's not good practice to directly create a class that extends JFrame
. Also, please read this too, for more clarification.