8

I have a JPanel containing JButtons and a few other things, and I want the entire panel to have a tool-tip. When I call setToolTipText on the JPanel, the tool-tip only appears in empty spaces within the JPanel.

Is there a way to set a tool-tip on the JPanel such that it applies to the JPanel and its children, or am I stuck with calling setToolTipText on all the children as well?

Arthur Ward
  • 597
  • 3
  • 20
  • 1
    hard to say something better ... http://stackoverflow.com/questions/7138914/swing-how-to-create-a-custom-jtooltip-like-widget-that-moves-with-the-mouse/7139057#comment-8561297, but maybe I'm wong – mKorbel Aug 30 '11 at 20:20

1 Answers1

8

Create a recursive method:

public static void setToolTipRecursively(JComponent c, String text) {

    c.setToolTipText(text);

    for (Component cc : c.getComponents())
        if (cc instanceof JComponent)
            setToolTipRecursively((JComponent) cc, text);
}

Full example:

public static void main(String[] args) {

    final JFrame frame = new JFrame("Test");

    frame.add(new JLabel("Testing (no tooltip here)"), BorderLayout.NORTH);

    final JPanel panel = new JPanel(new GridLayout(2, 1));
    panel.setBackground(Color.RED);

    panel.add(new JLabel("Hello"));
    panel.add(new JTextField("World!"));

    setToolTipRecursively(panel, "Hello World!");

    frame.add(panel, BorderLayout.CENTER);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
}
dacwe
  • 43,066
  • 12
  • 116
  • 140
  • In this solution, the tooltip flickers and changes position when crossing between subcomponents. I've posted a follow-up question about how it might be possible to treat the container as a single unit: http://stackoverflow.com/q/8592264/411282 – Joshua Goldberg Dec 21 '11 at 15:33
  • This breaks listening for clicks on the upper component. – KTibow Mar 13 '22 at 15:41