java lookandfeel nimbus,如何使用Nimbus LookAndFeel更改JToolTip的背景颜色?

In a Swing-based Java application using Nimbus LookAndFeel I try to set the background color of my tooltips. So I created a subclass of JToolTip and used it in my components by overriding createToolTip(). Fine so far and the tooltip is shown correctly, but the background color does not change. The foreground color is set as expected.

When changing the LookAndFeel to e.g. Metal I can set colors as expected.

Here a small example with ability to switch between Metal and Nimbus. As yopu hopefully see, the background color of the button's tooltip is only set when Metal is used.

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();

}

}

}

解决方案

The following also works for the Metal LAF without overriding the createToolTip() method:

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

LAF's can choose whether to use the UIManager properties or not. I have no idea if this will work with Nimbus.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值