1
我有一个JTable,其中显示一些使用html格式化的字符串数据。我需要显示鼠标指针Java Swing:基于鼠标指针下的文本显示JTable中的工具提示
在鼠标移到“线路1”和“2号线”我需要显示不同的工具提示下,基于文本的工具提示。有没有办法实现这一点,或者我必须使用自定义渲染器来渲染每一行的单元格和显示工具提示的基础上呢?
这里的示例代码来创建表
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();
}
});
}
}
但我仍然只能得到单元格中的整个值(这是'行1
行2'),而不是实际的行? – Krishnaraj 2012-04-29 06:17:49
不,您应该能够确定在哪个线路上使用鼠标事件中的点。请参阅JTextComponent#viewToModel和JTextArea#getLineOfOffset (哦,那需要您使用JTextArea进行渲染而不是JLabel) – 2012-05-01 09:22:44
我还没有时间完全尝试这一点,但使用JEditorPane可能会比JTextArea更好我正在使用HTML。我接受这个答案,因为它足够接近:) – Krishnaraj 2012-05-12 14:36:46