天天看點

java jtable 自動高度_java – 具有自動高度的多行JTable單元 – 超大的第一行

我正在使用Swing開發Java桌面應用程式(jdk1.6).我的問題是關于JTable中具有自動調整單元格高度屬性的多行單元格(文本換行).

我已經可以用這種方式實作這個結構了:

> Table有自己的cellrenderer.

>單元格是帶有wraptext = true的JTextArea

>我在将文本插入單元格後計算JTextArea中的行,并相應地調整相關行的行高.

>單元格寬度自動調整. (從首選尺寸)

關于這種結構的2個問題:

1)在程式執行期間,它可以對行進行計數并正确調整行高.

但是在第一次初始化時(第一個setModel()),它計算表的“第一個單元”的行數,即(0,0),遠遠超過它.我調試了代碼并發現它計算文本中的字母并乘以行高16.(好像單元格的寬度是1個字母).最後,我獲得了非常高的第一排.其他行都可以.

當我沒有向(0,0)插入任何文本時,不會出現問題.

2)當我禁用表自動調整大小屬性并手動确定單元格寬度時,行計數不起作用.

這是我的單元格渲染器:

public class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {

private JTable DependentTable;

public MultiLineCellRenderer() {

DependentTable=null;

setLineWrap(true);

setWrapStyleWord(true);

setOpaque(true);

}

public Component getTableCellRendererComponent(JTable table, Object value,

boolean isSelected, boolean hasFocus, int row, int column) {

(...) //some background color adjustments

setText((value == null) ? "" : value.toString());

int numOfLines = getWrappedLines(this); // Counting the lines

int height_normal = table.getRowHeight(row);// read the height of the row

if(DependentTable == null) // for this case always null

{

if (height_normal < numOfLines*16)

{

table.setRowHeight(row,numOfLines*16);

}

}

else

(...)

return this;

}

這是我如何計算行數:

public static int getWrappedLines(JTextArea component)

{

View view = component.getUI().getRootView(component).getView(0);

int preferredHeight = (int)view.getPreferredSpan(View.Y_AXIS);

int lineHeight = component.getFontMetrics( component.getFont() ).getHeight();

return preferredHeight / lineHeight;

}

————————————

我将行調整代碼删除到了類的外部.該表現在有一個Model Listener.第一行在這個時候并不是非常大.調用此方法有效但問題是關于計算包裹的行.每次我用非常長的文本填充單元格時,行都被正确包裝但我的計數器傳回1.(包裝線計數器的代碼在上面.與渲染器中的相同.但它在那裡工作正常)

這是我的模特聽衆:

public class ModelListener implements TableModelListener {

JTable mainTable;

JTable depTable;

public ModelListener(JTable m, JTable d) {

mainTable = m;

depTable = d;

}

public ModelListener(JTable m){

mainTable = m;

depTable = null;

}

public void tableChanged(TableModelEvent tme) {

int fRow = tme.getFirstRow();

int col = tme.getColumn();

JTextArea cellArea = (JTextArea)mainTable.getDefaultRenderer(Object.class);

int numOfLines = getWrappedLines(cellArea); //countLines();

int height_normal = mainTable.getRowHeight(fRow);

System.out.println("h normal:"+height_normal);

System.out.println("numLines:"+numOfLines);

System.out.println("value:"+mainTable.getModel().getValueAt(fRow, col));

System.out.println("width:"+cellArea.getPreferredSize().width);

if(depTable == null)

{

if (height_normal < numOfLines*16)

{

mainTable.setRowHeight(fRow,numOfLines*16);

}

}

else

{

//(---)

}

mainTable.repaint();

}

印刷品的結果:

preferredHeight: 15 // from wrapped lines function

lineHeight: 15 // from wrapped lines function

h normal:25

numLines:1

value:looooooooooooooooooooooonng tesssssssssssssssssssssssst // appears to be 2 lines

width:104

提前緻謝 :)

ISIL