为什么自动调整rowheight在Jtable中不起作用

时间:2014-02-12 18:05:33

标签: java swing jtable tablecellrenderer preferredsize

我已经实现了updateRowHeights,自动调整Jtable中行的高度的方法, 但它不起作用,虽然我的代码到目前为止工作正常。我忘记了什么吗? (见:Auto adjust the height of rows in a JTable

这是我的代码:

import javax.swing.*;
import java.awt.*;

public class ExampleTable {
JTable textTable;

public JPanel createTable() {               
    JPanel totalGUI = new JPanel();

    //define titles for table
    String[] title = {"TITLE1", "TITLE2", "TITLE3"};

    //table data
    Object[][] playerdata = {       
    {new Integer(34), "Steve", "test test test"},
    {new Integer(32), "Patrick", "du hu hu hu hu hu hu hu uh u kkkkkk oooo pppp"},
    {new Integer(10), "Sarah", "xxxxxxxxxxxxx aaaaaaaaaa bbbbbbbbbbbbb dddddddddddd xxxxxxx gggewr  eeeeeeeeee ddd g fffffff zzzzzzz"},};

    //create object 'textTable'
    textTable = new JTable(playerdata,title);

    //set column width
    textTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 
    textTable.getColumnModel().getColumn(0).setPreferredWidth(45);
    textTable.getColumnModel().getColumn(1).setPreferredWidth(45);
    textTable.getColumnModel().getColumn(2).setPreferredWidth(200);
    textTable.setDefaultRenderer(String.class, new RowHeightCellRenderer());

    //adjust dynamically the Row height of each cell
    updateRowHeights();

    //put line breaks if string is longer than cell-width
    RowHeightCellRenderer dynRow = new RowHeightCellRenderer();
    textTable.getColumnModel().getColumn(2).setCellRenderer(dynRow);
    System.out.println(textTable.getPreferredSize().height);

    //scrollbar
    JScrollPane scrollPane = new JScrollPane(textTable);

    totalGUI.add(scrollPane);               
    return totalGUI;
}

private void updateRowHeights() {

    /* 
     * Auto adjust the height of rows in a JTable.
     * The only way to know the row height for sure is to render each cell 
     * to determine the rendered height. After your table is populated with 
     * data you can do:         
     *  
     */        
    for (int row = 0; row < textTable.getRowCount(); row++) {
        int rowHeight = textTable.getRowHeight();
        for (int column = 0; column < textTable.getColumnCount(); column++)
        {
            Component comp = textTable.prepareRenderer(textTable.getCellRenderer(row, column), row, column);
            System.out.println("Row: "+row+" Column: "+column+ " preferredHeight: "+comp.getPreferredSize().height);
            rowHeight = Math.max(rowHeight, comp.getPreferredSize().height);
            System.out.println("Row: "+row+" Column: "+column+ " RowHeight: "+rowHeight);
        }
        textTable.setRowHeight(row, rowHeight);
    }
}

private static void createAndShowGUI() {

    //create main frame
    JFrame mainFrame = new JFrame("");
    ExampleTable test = new ExampleTable();
    JPanel totalGUI = new JPanel();
    totalGUI = test.createTable();

    //visible mode
    mainFrame.add(totalGUI); //integrate main panel to main frame
    mainFrame.pack();
    mainFrame.setVisible(true);     
}


public static void main (String[] args) {               

    createAndShowGUI();     

}//main
}

import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;

这是RowHeightCellRenderer:

    public class RowHeightCellRenderer extends JTextArea implements TableCellRenderer
    {
      /**
         * 
         */
        private static final long serialVersionUID = 1L;

    public Component getTableCellRendererComponent (JTable table, 
                                                    Object value, 
                                                    boolean isSelected, 
                                                    boolean hasFocus, 
                                                    int row, 
                                                    int column )  {
          this.setText((String)value);
          this.setLineWrap(true); //line break if String longer than the cell width
        return this;
      }
    }

非常感谢提前!!

1 个答案:

答案 0 :(得分:3)

看看你的代码:

updateRowHeights();

//put line breaks if string is longer than cell-width
RowHeightCellRenderer dynRow = new RowHeightCellRenderer();
textTable.getColumnModel().getColumn(2).setCellRenderer(dynRow);

您更新行高,然后设置单元格渲染器 。因此更新方法显然不能使用预期的单元格渲染器。更改顺序:

//put line breaks if string is longer than cell-width
RowHeightCellRenderer dynRow = new RowHeightCellRenderer();
textTable.getColumnModel().getColumn(2).setCellRenderer(dynRow);

updateRowHeights();

在计算和应用派生单元格高度之前,必须确保设置影响单元格视觉外观的所有属性。


另一个问题是,AWT布局概念,即getPreferredSize(),与你需要查询“给定实际宽度下的首选高度”的自动换行概念不相符。您必须与Swing文本API进行交互才能执行此类查询:

private void updateRowHeights() {
    final TableColumnModel columnModel = textTable.getColumnModel();
    Insets i=null;
    for(int row = 0; row < textTable.getRowCount(); row++) {
        int rowHeight = textTable.getRowHeight();
        for(int column = 0; column < textTable.getColumnCount(); column++) {
            Component comp = textTable.prepareRenderer(
                textTable.getCellRenderer(row, column), row, column);
            final int height;
            if(comp instanceof JTextComponent) {
                final JTextComponent tc = (JTextComponent)comp;
                final View rootView = tc.getUI().getRootView(tc);
                i=tc.getInsets(null);
                rootView.setSize(columnModel.getColumn(column)
                    .getPreferredWidth()-i.left-i.right,
                    Integer.MAX_VALUE);
                height=(int)rootView.getPreferredSpan(View.Y_AXIS);
            }
            else height = comp.getPreferredSize().height;
            rowHeight = Math.max(rowHeight, height);
        }
        textTable.setRowHeight(row, rowHeight);
    }
}