Reputation: 1596
Above is what I want to achieve:
JFrame
is a fixed 400 width JPanel
.GridBagLayout
.JscrollPane
wrapping a JTable
.I have had many trials, all failed:
So I think the problem is with the JTable, it always make a prox. 300*300 rectangular as shown within the red line.
Today is another bad day with swing's setPreferredSize and setSize and all these size problems. Hope anyone could help, thanks!
private JPanel buildInfoPanel() {
JPanel panel = new JPanel();
panel.setVisible(false);
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
panel.setLayout(gbl);
label_player = new JLabel("label_player");
label_player.setBackground(Color.RED);
constraints.gridy = 0;
constraints.anchor = GridBagConstraints.NORTH;
gbl.setConstraints(label_player, constraints);
panel.add(label_player);
label_deck = new JLabel("label_deck");
label_deck.setBackground(Color.BLUE);
constraints.gridy++;
gbl.setConstraints(label_deck, constraints);
panel.add(label_deck);
JTable table = new JTable(new ShipTableModel());
table.setAutoCreateRowSorter(true);
table.setFillsViewportHeight(true);
table.getRowSorter().toggleSortOrder(2);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBorder(new LineBorder(Color.red));
constraints.gridy++;
constraints.weighty = 1;
gbl.setConstraints(scrollPane, constraints);
panel.add(scrollPane);
return panel;
}
class ShipTableModel extends AbstractTableModel {
private Ship[] ships = new Ship[0];
private String[] columnNames = {"id", "name", "lv", "hp", "舰队", "舰种", "mId"};
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public int getRowCount() {
return ships.length;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
}
Upvotes: 0
Views: 297
Reputation: 1193
Just set constraints.fill = GridBagConstraints.VERTICAL
for the JScrollPane
.
Upvotes: 0