I am trying to create a simple scrollable JTable with some arbitrary values and place it inside of a JPanel. I am experiencing some strange results where the JTable appears but shows only the column names and seems to squish the remaining rows. Also the table appears in the center of the panel and I would like it to be at the top.
// Panel to hold our layer information
JPanel layerPanel = new JPanel(new GridBagLayout());
layerPanel.setBackground(Color.LIGHT_GRAY);
layerPanel.setPreferredSize(new Dimension(200, 200));
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(0,5,0,5);
c.weightx = 1; c.weighty = 0.0;
c.fill = GridBagConstraints.BOTH;
c.gridx = 0; c.gridy = 0;
String[] columns = { "Show", "Layer" };
Object[][] data = {{"x", "Layer1"},
{"x", "Layer2"}};
// Construct our table to hold our list of layers
JTable layerTable = new JTable(data, columns);
layerTable.getColumnModel().getColumn(0).setPreferredWidth(64);
layerPanel.add(new JScrollPane(layerTable), c);
frame.add(layerPanel);
Any help is appreciated, the code works when I use a GridLayout(1,0) instead of using the GridBagLayout so I have a feeling that I am using it wrong.
Thank you for your time.
You are not setting any ‘weight’ in the Y axis, so your
JscrollPanewill not expand in that axis. You could use:to fix this.