I want to add some tooltips to only a certain text inside a JTextPane. As an example, if there is a reference link text inside the JTextPane I want to add a tooltip to that text to show the link. Is there any way I can achieve this functionality?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You can add a TooltipText to a JComponent, like a JTextPane, not to words or parts of the Component.
Normally a JTextPane can contain multiple links, so for which should the TooltipText show the link?
But you can add a Listener to the JTextPane, and remove the old Tooltip, and add a new one, if you detect a Link.
You can try loading of HTML pages in the jtextpane. Here is an example. More explanation about this example can be found here
Override: getToolTipText(MouseEvent event) method of the text pane.
Using the MouseEvent you can use the viewToModel(...) method to get the offest into the Document. Then you can get the attributes to determine if you are hovering over a link.
Or maybe an easier approach is to use the getCursor() method. When the cursor is the hand cursor you are over a link.
Then you can return the appropriate tool tip text for the current link.
Good question.
First Swing supports HTML, so to show tooltip with link you just have to say:
comp.setToolTipText("<html><a href='http://www.google.com'>google</a></html>");
The problem is making this tooltip clickable.
Unfortunately it is not done by Swing itself.
Tooltip is created by ToolTipManager. When you call setToolTipText() Jcomponent adds the instance of itself to shared instance of Tooltip manager that is responsible on showing the tooltip (using method
show()
that cannot be overridden. You cannot change the tooltip manager itself too.So, the best solution I can suggest is to do the following. You can listen to the AWT events using
Toolkit.getDefaultToolkit().addAWTEventListener()
So, when tooltip is being showed catch it, discover, and add mouse listener on it. This mouse listener will make the tooltip itself clickable.
Here is the exercise I have just written. You can use it as a reference. Good luck.