Java Swing How to - Show the tooltip of the parent component








Question

We would like to know how to show the tooltip of the parent component.

Answer

import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
/*www  .  j a va2 s .  c om*/
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.ToolTipManager;

public class Main {
  public static void main(String[] args) {
    JTextPane text = new JTextPane() {
      @Override
      public String getToolTipText() {
        return ((JComponent) getParent()).getToolTipText();
      }
      @Override
      public String getToolTipText(MouseEvent event) {
        return ((JComponent) getParent()).getToolTipText(event);
      }
    };
    text.setText("Lorem ipsum dolor sit");
    ToolTipManager.sharedInstance().registerComponent(text);

    JFrame frame = new JFrame("Testing");
    JPanel panel = new JPanel(new BorderLayout());
    panel.setToolTipText("tooltip from parent");
    frame.setContentPane(panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(text);
    frame.pack();
    frame.setVisible(true);
  }
}