I have a JList and want to change the tooltips, depending on the entry the mouse hovers over. I tried searching my problem on google, but had no success.
Basically i need to get the object i am currently hovering over.
Every help is appreciated
In order to do that, you have to extend JList and expose the tooltip text method. Here is an example program I found sometime ago using 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);
}
});
}
}
Hope this helps.
1) Assign a MouseListener
to all elements in question.
2) Implement the mouseEntered
method
3) Inside that method, use event.getSource()
to get the element that was hovered.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.