import java.awt.Font;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class MultiLineToolTipInsideJTableCell extends JFrame {
public static void main(String[] args) {
new MultiLineToolTipInsideJTableCell();
}
public MultiLineToolTipInsideJTableCell()
{
//initilize
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
//JTable
JTable commentTable = new JTable() {
//Implement table cell tool tips.
public String getToolTipText(MouseEvent e) {
String tip = null;
java.awt.Point p = e.getPoint();
int rowIndex = rowAtPoint(p);
int colIndex = columnAtPoint(p);
int realColumnIndex = convertColumnIndexToModel(colIndex);
try {
if (realColumnIndex == 2 && rowIndex!=0) { //comment row, exclude heading
tip = getValueAt(rowIndex, colIndex).toString();
}
} catch (RuntimeException e1) {
//catch null pointer exception if mouse is over an empty line
}
return tip;
}
};
commentTable.setFont(new Font("Dialog", 0, 11));
commentTable.setAutoscrolls(true);
commentTable.setOpaque(true);
commentTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
commentTable.setModel(new DefaultTableModel(new Object[][] {},
new String[] { "USER", "TIME", "COMMENT" }) {
@SuppressWarnings("unchecked")
Class[] types = new Class[] { java.lang.String.class,
java.lang.String.class, java.lang.String.class};
boolean[] canEdit = new boolean[] { false, false, false};
@SuppressWarnings("unchecked")
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
});
((DefaultTableModel) commentTable.getModel()).setRowCount(5);
commentTable.getModel().setValueAt("USERNAME", 0, 0);
commentTable.getModel().setValueAt("DATE", 0, 1);
commentTable.getModel().setValueAt("COMMENTS", 0, 2);
//generate table's content here
for (int i=1; i<=3; i++)
{
commentTable.getModel().setValueAt("User"+i, i, 0);
commentTable.getModel().setValueAt("Date"+i, i, 1);
//commentTable.getModel().setValueAt("short comment"+i, i, 2);
commentTable.getModel().setValueAt("A very loooooooooooooooooooooooooooooooooong comment. Would like to split it up into multiple lines."+i, i, 2);
}
//finalize
panel.add(commentTable);
this.add(panel);
this.setSize(400, 300);
this.setVisible(true);
}
}