我在 Stackoverflow 上发现了类似的问题,但是由于某种原因,当我尝试实施建议的内容时,我得到了一个奇怪的异常。
所以我试图动态调整 3 列的一些高度。
public class AcquisitionTechniquesPanel extends JPanel {
private static final long serialVersionUID = -3326535610858334494L;
public static final int SIZE_OF_TABLE = 8;
private final JTable table;
private JCheckBox acquisitionTechniquesDone;
private Object[][] tableData;
private final String[] columnNames;
public AcquisitionTechniquesPanel() {
this.columnNames = new String[] { ApplicationStrings.ID, ApplicationStrings.TYPE, "Foo", "Bar", "Biz", "Baz", "Boz", ApplicationStrings.NO_OF_AR_S };
this.table = new JTable(tableData, columnNames);
initGUI();
}
public void initGUI() {
table.setColumnSelectionAllowed(
table.setDragEnabled(false);
table.setOpaque(true);
table.getTableHeader().setReorderingAllowed(false);
table.setModel(new DefaultTableModel());
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(800, 320));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
table.getColumnModel().getColumn(2).setCellRenderer(new VariableRowHeightRenderer());
table.getColumnModel().getColumn(3).setCellRenderer(new VariableRowHeightRenderer());
table.getColumnModel().getColumn(4).setCellRenderer(new VariableRowHeightRenderer());
}
});
}
public static class VariableRowHeightRenderer extends JLabel implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setText(String.valueOf(value));
if(getPreferredSize().height > 1)
table.setRowHeight(row, getPreferredSize().height);
return this;
}
}
}
现在,当我运行这段代码时,由于某种原因,我得到java.lang.ArrayIndexOutOfBoundsException: 2 >= 0
了代码上的这个异常,table.getColumnModel().getColumn(2).setCellRenderer(new VariableRowHeightRenderer());
这很奇怪,因为表应该有 8 列。
有谁知道我做错了什么?
请注意,我只显示相关代码