以上是我想要实现的目标:
JFrame
以东的JPanel
。GridBagLayout
。JscrollPane
包裹JTable
。我做了很多次试验,都失败了:
所以我认为问题在于JTable,它始终是一个代理。如红线所示的300 * 300矩形。
今天是另一个糟糕的日子,有了swing的setPreferredSize和setSize以及所有这些大小的问题。希望有人能提供帮助,谢谢!
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;
}
}
答案 0 :(得分:0)
只需为constraints.fill = GridBagConstraints.VERTICAL
设置JScrollPane
。