Friday, September 14, 2007

Java: create a table that a cell can contains multilines.

By default, the container in a JTable cell for a string is a JTextField object that only show all the content in one line. Sometimes, we need to present multi-lines in one cell, so we have to overwrite the cell handle object. Here is a sample for it.

The sequence is that overwrite the abstractTableModel, then overwrite the DefaultTableCellRender.

private DefaultTableModel getLogModel(){
if(logTblModel == null){
logTblModel = new DefaultTableModel() {
public boolean isCellEditable(int row, int colum) {
return false;
}
};

for(TITLE t : TITLE.values()){
logTblModel.addColumn(t.getName());
}
}
return logTblModel;
}


private JTable getTblLogRec() {
if (tblLogRec == null) {
tblLogRec = new JTable(getLogModel());
tblLogRec.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tblLogRec.getColumn(TITLE.TIME.getName()).setPreferredWidth(100);
tblLogRec.getColumn(TITLE.LEVEL.getName()).setPreferredWidth(50);
tblLogRec.getColumn(TITLE.MESSAGE.getName()).setPreferredWidth(375);
tblLogRec.getColumnModel().getColumn(TITLE.MESSAGE.ordinal()).setCellRenderer(new DefaultTableCellRenderer() {
private JTextPane _sumaryTxtPane;
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
getSumaryTxtPane().setText((String) value);
TableColumnModel columnModel = table
.getColumnModel();
getSumaryTxtPane().setSize(
columnModel.getColumn(column).getWidth(),
100000);
int heightWanted = (int) getSumaryTxtPane()
.getPreferredSize().getHeight();
if (heightWanted != table.getRowHeight(row)) {
table.setRowHeight(row, heightWanted);
}
if(isSelected){
getSumaryTxtPane().setBackground(getTblLogRec().getSelectionBackground());
}else{
getSumaryTxtPane().setBackground(getTblLogRec().getBackground());
}
return getSumaryTxtPane();
}

private JTextPane getSumaryTxtPane() {
if (null == _sumaryTxtPane) {
_sumaryTxtPane = new JTextPane();
}
return _sumaryTxtPane;
}
});
}
return tblLogRec;
}
}

No comments: