Trying to build a really simple UI with GridBagLayout, but when using setVisible(false/true) on Easy/Medium/Hard buttons, as expected the whole thing explodes. How do I set the textfield to be on top of the Check button? I did read the doc but having hard time grasping the logic behind all the GridBagLayout variables.
Left picture: Normal state
Right picture: When one of the buttons (easy/medium/hard) has been clicked
Code:
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridbag);
c.weightx = 4;
c.weighty = 4;
c.anchor = GridBagConstraints.PAGE_END;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 6;
JButton check = buttonFactory("Check", gridbag, c);
c.gridx = 1;
c.gridy = 6;
JButton easy = buttonFactory("Easy", gridbag, c);
c.gridx = 2;
c.gridy = 6;
JButton medium = buttonFactory("Medium", gridbag, c);
c.gridx = 3;
c.gridy = 6;
JButton hard = buttonFactory("Hard", gridbag, c);
c.gridx = 2;
c.gridy = 4;
c.anchor = GridBagConstraints.CENTER;
JLabel question = labelFactory(gridbag, c);
c.anchor = GridBagConstraints.CENTER;
c.ipady = 30;
c.gridwidth = 4;
c.gridx = 0;
c.gridy = 5;
JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL);
gridbag.setConstraints(separator, c);
add(separator);
c.gridx = 2;
c.gridy = 5;
c.anchor = GridBagConstraints.PAGE_END;
JLabel answer = labelFactory(gridbag, c);
c.gridwidth = 1;
c.gridx = 2;
c.gridy = 6;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
JTextField userInput = new JTextField();
gridbag.setConstraints(userInput, c);
add(userInput);
I'm not really sure I understand your layout. It seems like you are trying to replace 3 buttons with a single button. If so, then use a different layout.
The Card Layout
was designed to allow you to swap panels containing different components. Read the section from the Swing tutorial on How to Use Card Layout for more information.
The tutorial also has a section on How to Use GridBag Layout
, which will explain the constraints in more detail.