-
JTable multiline
Hi,
I want to make a new line in a cell when i press the ENTER key (multiline).
------------------
| line | a |
| line | a |
------------------
| b | b |
------------------
For a new table line i have a button.
this is my code:
Code:
private static class TextTableCellRenderer extends JTextArea implements TableCellRenderer {
protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);
public TextTableCellRenderer() {
super();
setWrapStyleWord(true);
setLineWrap(true);
setBorder(noFocusBorder);
}
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
if (isSelected) {
super.setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else {
super.setForeground(table.getForeground());
super.setBackground(table.getBackground());
}
setFont(table.getFont());
if (hasFocus) {
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
if (!isSelected && table.isCellEditable(row, column)) {
Color col;
col = UIManager.getColor("Table.focusCellForeground");
if (col != null) {
super.setForeground(col);
}
col = UIManager.getColor("Table.focusCellBackground");
if (col != null) {
super.setBackground(col);
}
}
} else {
setBorder(noFocusBorder);
}
setEnabled(table.isEnabled());
setValue(table, row, column, value);
return this;
}
protected void setValue(JTable table, int row, int column, Object value) {
if (value != null) {
String text = value.toString();
setText(text);
View view = getUI().getRootView(this);
view.setSize((float) table.getColumnModel().getColumn(column).getWidth() - 3, -1);
float y = view.getPreferredSpan(View.Y_AXIS);
int h = (int) Math.ceil(y + 3);
if (table.getRowHeight(row) != h) {
table.setRowHeight(row, h);
}
} else {
setText("");
}
}
}
thanks
iceT
-
If you look at the api for DefaultTableCellRenderer, you will see that it is a JLabel with certain methods stubbed out for performance reasons. You can make your own TableCellRenderer using any Component by stubbing out the same methods.TableCellEditor is a subclass of Renderer that allows user input with a little code to handle saving the contents when editing is stopped.
Look at the multi-line text JComponents offered by Swing. Try making your own Renderer from the interface (it only has the one method) by extending a JTextArea and implementing the interface. Check the api for the methods to stub off.