我正在尝试实现自定义 TableRenderer,如 this tutorial 中所述。 . 我想让渲染器对给定单元格长的每个文本进行换行。 这个想法是,使用 TextArea 作为渲染器,因为它支持换行。但是,以下代码的行为与预期不同:
public class LineWrapCellRenderer extends JTextArea implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
this.setText((String)value);
this.setWrapStyleWord(true);
this.setLineWrap(true);
return this;
}
}
我用
设置这个渲染器table.setDefaultRenderer(String.class, new LineWrapCellRenderer());
但单元格条目保持未包装。
如果我将 this.setBackground(Color.YELLOW)
添加到 getTableCellRendererComponent()
方法中,
所有单元格都按预期显示为黄色,但未包裹。
有什么想法吗?
更新: 正如 Michael Borgwardt 在评论中所说,问题不是换行,而是行高:JTables 行是固定大小的,所以如果一个单元格越来越高(导致文本现在是多行的),我们必须增加行高。 但是多少钱?我会检查这是否值得另一个 SO 问题。如果没有,我将在此处添加此解决方案。
Update2:以下代码将确定行高(如果放在getTableCellRendererComponent()
中):
int fontHeight = this.getFontMetrics(this.getFont()).getHeight();
int textLength = this.getText().length();
int lines = textLength / this.getColumns() +1;//+1, cause we need at least 1 row.
int height = fontHeight * lines;
table.setRowHeight(row, height);
最佳答案
问题在于 JTable 中的行高是固定的,所以这不仅仅是一个渲染器的问题;我不知道为什么它不这样做,但如果是这样,包装的文本将被裁剪 - 或者这正是你所看到的。要调整行高,您需要单独设置它们。
int rows = 10;
int cols = 5;
JTable table = new JTable(rows, cols);
// Set the 1st row to 60 pixels high
table.setRowHeight(0, 60);
// Set the height of all rows to 32 pixels high,
// regardless if any heights were assigned to particular rows
table.setRowHeight(32);
// the height of the 1st row is set to 32 pixels high
// Returns the preferred height of a row.
// The result is equal to the tallest cell in the row.
public int getPreferredRowHeight(JTable table, int rowIndex, int margin) {
// Get the current default height for all rows
int height = table.getRowHeight();
// Determine highest cell in the row
for (int c=0; c<table.getColumnCount(); c++) {
TableCellRenderer renderer = table.getCellRenderer(rowIndex, c);
Component comp = table.prepareRenderer(renderer, rowIndex, c);
int h = comp.getPreferredSize().height + 2*margin;
height = Math.max(height, h);
}
return height;
}
// The height of each row is set to the preferred height of the
// tallest cell in that row.
public void packRows(JTable table, int margin) {
packRows(table, 0, table.getRowCount(), margin);
}
// For each row >= start and < end, the height of a
// row is set to the preferred height of the tallest cell
// in that row.
public void packRows(JTable table, int start, int end, int margin) {
for (int r=0; r<table.getRowCount(); r++) {
// Get the preferred height
int h = getPreferredRowHeight(table, r, margin);
// Now set the row height using the preferred height
if (table.getRowHeight(r) != h) {
table.setRowHeight(r, h);
}
}
}
关于java - 如何在 jtable 单元格中换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/965023/