I'm learning how to make GUIs on IntelliJ but the frame I make doesn't appear when I run the program. I've tried making the main folder a source root, changing the settings and adding a bit of code but it doesn't want to work. Right now all Im trying to make is a panel with a button, that's it. I'd appreciate if someone could help, thanks:)
This is the code, I don't know why it's getting formated all weird, sorry.
public class Game extends JFrame {
private JPanel panel;
private JButton button1;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setContentPane(new Game().panel);
frame.pack();
frame.setVisible(true);
}
}
You need to initialize JPanel and JButton and add them on JFrame using "add" method. For example:
public class Game extends JFrame {
private static JPanel panel;
private static JButton button1;
public static void main(String[] args) {
panel = new JPanel();
button1 = new JButton("Test");
panel.add(button1);
JFrame frame = new JFrame();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
For anyone who might have the same problem I was having. I just needed to add some code to the main class.
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new Game();
frame.setSize(300,300);
frame.setVisible(true);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.