我有一个JList,想要更改工具提示,具体取决于鼠标悬停的条目。我尝试在谷歌搜索我的问题,但没有成功。
基本上我需要得到我正在徘徊的物体。
感谢每一位帮助
答案 0 :(得分:4)
为此,您必须扩展JList并公开工具提示文本方法。以下是我之前使用Google发现的示例程序:
import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;
// Custom class to extend our JList and expose tooltip functionality.
class MyList extends JList {
public MyList() {
super();
// Attach a mouse motion adapter to let us know the mouse is over an item and to show the tip.
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
MyList theList = (MyList) e.getSource();
ListModel model = theList.getModel();
int index = theList.locationToIndex(e.getPoint());
if (index > -1) {
theList.setToolTipText(null);
String text = (String) model.getElementAt(index);
theList.setToolTipText(text);
}
}
});
}
// Expose the getToolTipText event of our JList
public String getToolTipText(MouseEvent e) {
return super.getToolTipText();
}
}
public class TestJList extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
TestJList myTest = new TestJList();
myTest.setTitle("Example JList");
myTest.setSize(300, 300);
myTest.setDefaultCloseOperation(EXIT_ON_CLOSE);
MyList list = new MyList();
// Create our model and add some items.
DefaultListModel model = new DefaultListModel();
model.addElement("one");
model.addElement("two");
model.addElement("three");
model.addElement("four");
// Set the model for our list
list.setModel(model);
ToolTipManager.sharedInstance().registerComponent(list);
// Add our custom list and show the form.
MyTest.add(list);
MyTest.setVisible(true);
}
});
}
}
希望这有帮助。
答案 1 :(得分:3)
1)为所有相关元素分配MouseListener
2)实施mouseEntered
方法
3)在该方法中,使用event.getSource()
来获取悬停的元素。