在使用Nimbus LookAndFeel的基于Swing的Java应用程序中,我尝试设置工具提示的背景颜色。因此,我创建了JToolTip的子类,并通过覆盖createToolTip()在我的组件中使用它。到目前为止都很好,工具提示正确显示,但是背景颜色没有改变。前景颜色按预期设置。
当将LookAndFeel更改为例如Metal时,可以按预期设置颜色。
以下是一个小示例,具有在Metal和Nimbus之间切换的功能。希望您能看到,只有在使用Metal时才设置了按钮工具提示的背景颜色。
以下是一个小示例,具有在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();
}
}
}
ex.printStackTrace()
不仅比注释更简短,而且更有用。3)我不知道如何解决问题。我让Swing专家来处理,希望他们很快会出现。 - Andrew Thompson