Java swing gridbaglayout – add a button without spaces
How to delete the spacing caused by gridbaglayout and make them stick together?
import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class MyProblem { private JFrame frame = new JFrame(); public static void main(String[] args) { new MyProblem(); } public MyProblem() { frame.setLayout(new GridBagLayout()); GridBagConstraints gc = new GridBagConstraints(); gc.weightx = 1; gc.weighty = 1; gc.gridx = 0; gc.gridy = 0; gc.fill = GridBagConstraints.HORIZONTAL; gc.anchor = GridBagConstraints.NORTH; for (int i = 0; i < 3; i++) { JPanel jPanel = new JPanel(new BorderLayout()); jPanel.setSize(80,80); jPanel.add(new JButton("Button " + i),BorderLayout.PAGE_START); frame.add(jPanel,gc); gc.gridy++; } frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500,500); frame.setVisible(true); } }
How do my buttons:
I want my buttons to look like:
Solution
The layout will produce a list of buttons, so
Change:
gc.fill = GridBagConstraints.HORIZONTAL;
To:
gc.fill = GridBagConstraints.BOTH;
Edit 1
It's fairly easy to limit them to the top using a composite layout In this case, we might add a panel with buttons to the page of a panel with borderlayout_ In start That part of the border layout will stretch the width of the sub components (our panel and GridLayout) to fill the available space, but it will respect the height of any content - providing the required vertical space for the components
Edit 2
This is an mcve to realize the above idea The outer panel (with cyan border) is used to constrain the height of the button panel (with orange border) For more details on how it works, see the comments in the source code
import java.awt.*; import javax.swing.*; import javax.swing.border.LineBorder; public class MyProblem { private JFrame frame = new JFrame(); public static void main(String[] args) { new MyProblem(); } public MyProblem() { frame.setLayout(new BorderLayout()); // actually the default // we will use this panel to constrain the panel with buttons JPanel ui = new JPanel(new BorderLayout()); frame.add(ui); ui.setBorder(new LineBorder(Color.CYAN,3)); // the panel (with GridLayout) for the buttons JPanel toolPanel = new JPanel(new GridLayout(0,1,4)); // added some gap toolPanel.setBorder(new LineBorder(Color.ORANGE,3)); // toolPanel will appear at the top of the ui panel ui.add(toolPanel,BorderLayout.PAGE_START); for (int i = 0; i < 3; i++) { toolPanel.add(new JButton("Button " + i)); } frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); //frame.setSize(500,500); // instead.. frame.pack(); // pack will make it as small as it can be. frame.setMinimumSize(frame.getSize()); // nice tweak.. frame.setVisible(true); } }