简体   繁体   English

在JTable上动态调整行高

[英]Adjusting row height dynamically on JTable

I have found similar questions here on Stackoverflow, but for some reason when I try to implement what is suggested, I get a strange exception. 我在Stackoverflow上发现了类似的问题,但是由于某种原因,当我尝试实现建议的内容时,出现了一个奇怪的异常。

So I am trying to get adjust some of the heights on 3 of the columns dynamically. 因此,我试图动态调整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;
        }
    }
}

Now when I run this code, for some reason I get java.lang.ArrayIndexOutOfBoundsException: 2 >= 0 I get this exception on the code table.getColumnModel().getColumn(2).setCellRenderer(new VariableRowHeightRenderer()); 现在,当我运行这段代码时,由于某种原因,我得到了java.lang.ArrayIndexOutOfBoundsException: 2 >= 0我在代码table.getColumnModel().getColumn(2).setCellRenderer(new VariableRowHeightRenderer());上得到了这个异常table.getColumnModel().getColumn(2).setCellRenderer(new VariableRowHeightRenderer()); Which is strange, because the table should have 8 columns. 这很奇怪,因为表应该有8列。

Does anyone know what I am doing wrong? 有人知道我在做什么错吗?

Please note that I am only showing relevant code 请注意,我只显示相关代码

The problem comes from here: 问题来自这里:

table.setModel(new DefaultTableModel());

You set an empty model on your JTable and therefore overwrite the implicit model you have created with the JTable constructor. 您在JTable上设置了一个空模型,因此覆盖了使用JTable构造函数创建的隐式模型。 Simply remove that line and you should have your 8 columns. 只需删除该行,您应该拥有8列。

Btw, there is no need to wrap your call in an invokeLater. 顺便说一句,您无需将调用包装在invokeLater中。

Below is an excerpt of SwingX' TableUtilies which provide the height adjustment. 以下是SwingX的TableUtilies的摘录,其中提供了高度调整功能。 You use it like 你用它像

this.table = new JTable(tableData, columnNames);
// initial sizing
TableUtilites.setPreferredRowHeights(table);
TableModelListener l = new TableModelListener() {
     public void tableChanged(...) {
         // dynamic sizing on changes
         SwingUtilities.invokeLater() {
              public void run() {
                  TableUtilities.setPreferredRowHeights(table);
              }
         };
     }
}; 
table.getModel().addTableModelListener(l);

Utility methods from TableUtilities: TableUtilities的实用程序方法:

/**
 * Returns the preferred height for the given row. It loops
 * across all visible columns and returns the maximal pref height of
 * the rendering component. Falls back to the table's base rowheight, i
 * f there are no columns or the renderers
 * max is zeor.<p>
 * 
 * @param table the table which provides the renderers, must not be null
 * @param row the index of the row in view coordinates
 * @return the preferred row height of
 * @throws NullPointerException if table is null.
 * @throws IndexOutOfBoundsException if the row is not a valid row index
 */
public static int getPreferredRowHeight(JTable table, int row) {
    int pref = 0;
    for (int column = 0; column < table.getColumnCount(); column++) {
        TableCellRenderer renderer = table.getCellRenderer(row, column);
        Component comp = table.prepareRenderer(renderer, row, column);
        pref = Math.max(pref, comp.getPreferredSize().height);
    }
    return pref > 0 ? pref : table.getRowHeight();
}

/**
 * 
 * @param table the table which provides the renderers, must not be null
 * @param row the index of the row in view coordinates
 * @throws NullPointerException if table is null.
 * @throws IndexOutOfBoundsException if the row is not a valid row index
 */
public static void setPreferredRowHeight(JTable table, int row) {
    int prefHeight = getPreferredRowHeight(table, row);
    table.setRowHeight(row, prefHeight);
}

/**
 * Sets preferred row heights for all visible rows. 
 * 
 * @param table the table to set row heights to
 * @throws NullPointerException if no table installed.
 */
public static void setPreferredRowHeights(JTable table) {
    // care about visible rows only
    for (int row = 0; row < table.getRowCount(); row++) {
        setPreferredRowHeight(table, row);
    }
}
  • remove, disable or change code line table.setColumnSelectionAllowed( 删除,禁用或更改代码行表table.setColumnSelectionAllowed(

  • assume that ApplicationStrings.XXX are global variables that returns String value (or "" ) 假设ApplicationStrings.XXX是返回String值(或"" )的全局变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM