How to set up tooltip on JPanel and its children?

I have a JPanel containing JButtons and a few other things, and I want the whole panel to have a hint. When I call setToolTipText on a JPanel, the tooltip appears only in the empty spaces inside the JPanel.

Is there a way to set the tooltip on JPanel so that it applies to JPanel and its children, or am I stuck in calling setToolTipText on all children?

+6
source share
1 answer

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); } 
+7
source

Source: https://habr.com/ru/post/896245/


All Articles