我有一个 JTable,我在其中显示一些使用 html 格式化的字符串数据。我需要根据鼠标指针下的文本显示工具提示
在鼠标悬停在“Line1”和“Line2”上时,我需要显示不同的工具提示。有什么方法可以实现这一点,还是我必须使用自定义渲染器用一个单元格渲染每一行并根据它显示工具提示?
这是创建表的示例代码
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();
}
});
}
}