在使用 Nimbus LookAndFeel 的基于 Swing 的 Java 应用程序中,我尝试设置工具提示的背景颜色。所以我创建了一个 JToolTip 的子类,并通过覆盖 createToolTip() 在我的组件中使用它。到目前为止很好,工具提示显示正确,但背景颜色没有改变。前景色按预期设置。
将 LookAndFeel 更改为例如时金属 我可以按预期设置颜色。

这是一个能够在 Metal 和 Nimbus 之间切换的小例子。正如你所希望看到的,按钮工具提示的背景颜色仅在使用 Metal 时设置。

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolTip;

public class TooltipTestApp {

private static final String METAL_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
private static final String NIMBUS_LOOK_AND_FEEL = "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel";
private static JButton button;
private static String usedLookAndFeel = NIMBUS_LOOK_AND_FEEL;

    public static void main(String args[]) {
        button = new JButton() {

            @Override
            public JToolTip createToolTip() {
                JToolTip toolTip = super.createToolTip();
                toolTip.setBackground(Color.BLACK);
                toolTip.setForeground(Color.RED);

                    return toolTip;
            }
        };

        button.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TooltipTestApp.toggleLookAndFeel();
            }
        });

        button.setToolTipText("Some text");

        JFrame frame = new JFrame("TooltipTestApp");

        TooltipTestApp.toggleLookAndFeel();
        frame.add(button);
        frame.setSize(450, 100);
        frame.setVisible(true);
    }

    private static void toggleLookAndFeel() {
        try {
            if (usedLookAndFeel.equals(METAL_LOOK_AND_FEEL)) {
                usedLookAndFeel = NIMBUS_LOOK_AND_FEEL;
            } else {
                usedLookAndFeel = METAL_LOOK_AND_FEEL;
            }

            UIManager.setLookAndFeel(usedLookAndFeel);

            String lookAndFeelName = usedLookAndFeel.substring(usedLookAndFeel.lastIndexOf(".") + 1);
            button.setText("This is: " + lookAndFeelName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

最佳答案

以下也适用于 Metal LAF,无需覆盖 createToolTip() 方法:

UIManager.put("ToolTip.background", Color.RED);

LAF 可以选择是否使用 UIManager 属性。我不知道这是否适用于 Nimbus。

关于java - 如何使用 Nimbus LookAndFeel 更改 JToolTip 的背景颜色?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7807411/

10-12 00:27
查看更多