I would like to make it so that a user can select text that they've previously written into a textArea, then afterwards they would be able to select it and add a tooltip that would appear when hovering said text.
I tried to make it but i've only managed to have it show the tooltip when hovering anywhere inside of the textArea, meaning that whenever a tooltip is created, it will be shown if the mouse hovers inside of the textArea, irregardless of where it hovers, as opposed to having it only show the tooltip when the mouse hovers the string that it was created in.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
public class toolTip extends JFrame {
private JTextArea textArea;
private JPopupMenu popupMenu;
private TooltipManager tooltipManager;
public toolTip() {
setTitle("Custom Tooltip Application");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea();
tooltipManager = new TooltipManager(textArea);
popupMenu = new JPopupMenu();
JMenuItem addTooltipItem = new JMenuItem("Add Tooltip");
addTooltipItem.addActionListener(e -> addTooltip());
popupMenu.add(addTooltipItem);
textArea.setComponentPopupMenu(popupMenu);
add(new JScrollPane(textArea), BorderLayout.CENTER);
}
private void addTooltip() {
String selectedText = textArea.getSelectedText();
if (selectedText != null && !selectedText.isEmpty()) {
String tooltip = JOptionPane.showInputDialog("Enter tooltip text:");
if (tooltip != null && !tooltip.isEmpty()) {
tooltipManager.addTooltip(selectedText, tooltip);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new toolTip().setVisible(true));
}
}
class TooltipManager {
private JTextArea textArea;
private Map<String, String> tooltips = new HashMap<>();
public TooltipManager(JTextArea textArea) {
this.textArea = textArea;
textArea.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
updateTooltip(e);
}
});
}
public void addTooltip(String text, String tooltip) {
tooltips.put(text, tooltip);
}
private void updateTooltip(MouseEvent e) {
String word = getWordAtPoint(e.getPoint());
if (word != null && tooltips.containsKey(word)) {
textArea.setToolTipText(tooltips.get(word));
} else {
textArea.setToolTipText(null);
}
}
private String getWordAtPoint(Point p) {
int pos = textArea.viewToModel2D(p);
String text = textArea.getText();
int start = findWordStart(text, pos);
int end = findWordEnd(text, pos);
return text.substring(start, end);
}
private int findWordStart(String text, int pos) {
while (pos > 0 && Character.isLetterOrDigit(text.charAt(pos - 1))) {
pos--;
}
return pos;
}
private int findWordEnd(String text, int pos) {
while (pos < text.length() && Character.isLetterOrDigit(text.charAt(pos))) {
pos++;
}
return pos;
}
}
