我有一个可编辑的 jtable。当用户在单元格中写入文本时,如果输入的文本更适合单元格的大小,则表格中行的高度必须增加以适应用户输入的新文本。你能告诉我如何根据输入的文本行增加行的高度吗?
谁能帮我解决这个问题? 我试图将 JTextArea 添加到一行中,但这不起作用。
最佳答案
您需要计算新输入文本所需的高度。根据您用于单元格的渲染器,您可以使用例如JTextArea.getLineCount()
找出文本包含多少行。
然后您需要检索渲染器使用的字体的高度,并从中计算出所需的高度。
获得该数字后,使用 JTable.setRowHeight(int, int)
更改特定行的高度。
像这样:
Component c = renderer.getTableCellRendererComponent(theTable, theTable.getValueAt(row, col), false, false, row, col);
Font f = c.getFont();
FontMetrics fm = c.getFontMetrics(f);
// this cast depends on the way your renderer is implemented !!!!
int lineCount = ((JTextArea)c).getLineCount();
int fheight = fm.getHeight();
int rowHeight = lineCount * fheight;
theTable.setRowHeight(row, rowHeight); //NOTE: rows and columns are zero-indexed
关于java - 如何根据单元格中输入的文本内容增加jtable中行的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8225946/