如何使用Nimbus LookAndFeel更改JToolTip的背景颜色?

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

这是一个能够在Metal和Nimbus之间切换的小例子。 正如yopu希望看到的那样,按钮工具提示的背景颜色仅在使用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。

尝试这个:

  public class Main { public static void main(String args[]) { JFrame frame = new JFrame("JToolTip Sample"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton b1 = new JButton("Button 1") { public JToolTip createToolTip() { JToolTip tip = super.createToolTip(); tip.setForeground(Color.YELLOW); tip.setBackground(Color.RED); tip.setFont(new Font("Arial", Font.BOLD,36)); return tip; } }; b1.setToolTipText("HELLO"); frame.add(b1, BorderLayout.NORTH); frame.setSize(300, 150); frame.setVisible(true); } } 

资料来源: http : //www.java2s.com/Code/Java/Swing-JFC/ModifythebehaviourofthedefaultJToolTip.htm