Я пытаюсь реализовать пользовательский TableRenderer, как описано в этот учебник. Я бы хотел, чтобы строка рендеринга обтекала каждый текст, который длится для данной ячейки. Идея состоит в том, чтобы использовать 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()
,
все ячейки желтые, как ожидалось, но не завернуты.
Любые идеи?
ОБНОВЛЕНИЕ: Как отметил Майкл Боргвардт в комментариях, проблема не в переносе строки, а в высоте строки: строки 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);