I have added my buttons to my JPanel and i want to make them appear in different areas in the Panel. I want to layout my Panel so that there are 3 buttons on top, and a question label stretching across the center.
I've tried multiple different Layouts but can't get the buttons in the right spots. The buttons always end up in the Center of the frame on the order that they were added.
public Frame(int w, int h) {
width = w;
height = h;
buttonY = new JButton("Yes");
buttonN = new JButton("No");
buttonIDK = new JButton("I don't know");
QL = new JLabel(question);
counter = new JLabel("Your question count is: " +count);
}
public void setUpFrame() {
JFrame f = new JFrame();
JPanel p = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
p.setLayout(new GridBagLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(width, height);
p.setSize(getPreferredSize());
f.setTitle("Food Akinator");
p.setBackground(Color.RED);
p.setBackground(Color.RED);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
p.add(buttonY, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTH;
p.add(buttonIDK, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTHEAST;
p.add(buttonN, c);
QL.setFont(new Font("Times New Roman", Font.PLAIN, 20));
QL.setText(question);
QL.setBorder(border);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.CENTER;
p.add(QL, c);
f.add(p);
f.setVisible(true);
}
GridBagLayoutis powerful but complicated. When practical, use simpler layout managers.BorderLayoutis a surprisingly useful layout manager. See tutorial by Oracle. The center part fills like a balloon to take all the room not needed by content in the surrounding parts.Put your buttons in the top part. Put your question label in the center part. Easy-peasy.
Remember that you can nest layouts within layouts. You may need to wrap your buttons in a layout, then place that layout within the top part of the
BorderLayout.