开发者

How do I set a tooltip on a JPanel and its children?

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 setToolTipTe开发者_如何学编程xt 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?


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜