I am making a GUI class using the gridbaglayout, which is fine. I want to make an object of this class and 'spawn' it from my main class. However when I run my main class, nothing happens at all. When I run my GUI class, the GUI shows up. What's going on here?
public class GUI extends JFrame {
JButton btnStart;
JPanel pnlRadio, pnlMain;
JLabel lblUsername, lblPassword, lblHerb;
JTextField txtUsername, txtPassword;
ButtonGroup btngrHerbs;
JRadioButton rdbHarralander, rdbRanarr, rdbToadflax;
GridBagConstraints gbc;
public GUI() {
pnlMain = new JPanel();
pnlMain.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
pnlRadio = new JPanel();
btnStart = new JButton("Start");
lblUsername = new JLabel("Username");
lblPassword = new JLabel("Password");
txtUsername = new JTextField();
txtPassword = new JTextField();
btngrHerbs = new ButtonGroup();
rdbHarralander = new JRadioButton("Harralander");
rdbRanarr = new JRadioButton("Ranarr");
rdbToadflax = new JRadioButton("Toadflax");
// Some layout stuff for gridbagconstraints, etc
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
pnlMain.add(btnStart, gbc);
btnStart.addActionListener(e ->{
synchronized(Main.lock){
Main.lock.notify();
}
this.setVisible(false);
});
}
public JPanel getUI() {
return pnlMain;
}
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
JFrame frame = new JFrame("Example");
frame.getContentPane().add(new GUI().getUI());
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
And then there is the main class:
public class Main {
static Object lock = new Object();
static GUI gui = new GUI();
public static void main(String[] args) {
synchronized(lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A");
}
}
So when I run the GUI class nothing really happens. The GUI shows up as expected, but of course nothing happens when I click my button. When I start up the main class, the GUI doesn't even appear and I'm not getting "A" printed on the console either. So it seems to be stuck waiting for that lock object?
What I want is the main class to wait for the button to be pressed, then set the GUI visible to false and save some values in variables. How can I achieve this?
pack()beforesetVisible(); construct and manipulate Swing GUI objects only on the event dispatch thread.