概要
JTable
のセル内に文字列を二行分だけ表示し、あふれる場合は...
で省略します。
サンプルコード
JTable table = new JTable(model);
table.setAutoCreateRowSorter(true);
table.setRowHeight(table.getRowHeight() * 2);
table.setDefaultRenderer(String.class, new TwoRowsCellRenderer());
//...
class TwoRowsCellRenderer extends JPanel implements TableCellRenderer {
private final JLabel top = new JLabel();
private final JLabel bottom = new JLabel();
public TwoRowsCellRenderer() {
super(new GridLayout(2, 1, 0, 0));
add(top);
add(bottom);
}
@Override public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setFont(table.getFont());
FontMetrics fm = table.getFontMetrics(table.getFont());
String text = Objects.toString(value, "");
String first = text;
String second = "";
//int columnWidth = table.getColumnModel().getColumn(column).getWidth();
int columnWidth = table.getCellRect(0, column, false).width;
int textWidth = 0;
for (int i = 0; i < text.length(); i++) {
textWidth += fm.charWidth(text.charAt(i));
if (textWidth > columnWidth) {
first = text.substring(0, i - 1);
second = text.substring(i - 1);
break;
}
}
top.setText(first);
bottom.setText(second);
return this;
}
}
view all解説
JLabel
を上下に配置したJPanel
を使って、TableCellRenderer
を作成しています。...
での省略は、2
行目のJLabel
のデフォルト動作です。
- 補助文字(サロゲートペアなど)を含む文字列を扱う場合は、
String#charAt(int)
ではなく、String#codePointAt(int)
やCharacter.charCount(codePoint)
などを使用する必要がある
int i = 0;
while (i < text.length()) {
int cp = text.codePointAt(i);
textWidth += fm.charWidth(cp);
if (textWidth > columnWidth) {
first = text.substring(0, i);
second = text.substring(i);
break;
}
i += Character.charCount(cp);
}