以上是我想要达到的目标:
JFrame
的东部是一个固定的400宽度的JPanel
GridBagLayout
JTable
的JscrollPane
我有过许多试验,都失败了:
今天又是糟糕的一天,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;
}
}
只需设置< code > constraints . fill = GridBagConstraints。< code>JScrollPane的垂直。