Java Swing: display tooltip in JTable based on text under mouse pointer
I have a JTable where I am displaying some string data formatted using html. I need to show a tooltip based on the text under the mouse pointer
On the mouse over "Line1" and "Line2" I need to show different tooltips. Is there a way to achieve this or should I use my own renderer to render each row using a cell and show a hint based on that?
Here's a sample code to create a table
package com.sample.table;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
public class SampleTable {
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SampleTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(createTablePanel(), BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static JPanel createTablePanel(){
JPanel tablePanel = new JPanel();
JTable table = createTable();
table.setFillsViewportHeight(true);
table.setRowHeight(45);
addListener(table);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(300, 120));
tablePanel.add(scrollPane);
return tablePanel;
}
private static void addListener(JTable table) {
table.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
if(e.getSource() instanceof JTable){
JTable table = (JTable)e.getSource();
table.setToolTipText("Some tooltip");
}
}
@Override
public void mouseDragged(MouseEvent e) {
// do nothing
}
});
}
public static JTable createTable(){
String[] columnNames = {"Column1", "Column2"};
Object[][] data = {{"1", "<html>Line1<br/>Line2</html>"},
{"2", "<html>Line1<br/>Line2</html>"}};
JTable table = new JTable(data, columnNames);
return table;
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
source to share
Override the method of the getToolTipText(MouseEvent)
component returned by yours TableCellRenderer
. If you are extending DefaultTableCellRenderer
that extends JLabel
and returns itself as a render component, you can override it directly in your subclass.
You have to determine which line the mouse is using MouseEvent#getPoint()
. See JTextComponent#viewToModel
or JTextArea#getLineOfOffset
(if you are using JTextArea
for rendering instead JLabel
).
source to share