如何只更改一个组件的工具提示颜色?
我知道您可以执行以下操作来更改工具提示颜色:
UIManager.put("ToolTip.background", new ColorUIResource(255, 247, 200));
但这会更改所有组件的工具提示背景,而不仅仅是一个组件。
有什么简单的解决方案吗?
最佳答案
+1 给@MadProgrammer 和@Reimeus,以获得他们的建议和示例。
这些都是正确的。
添加...
没有默认方法可以做到这一点。您必须扩展 ToolTip
类,创建您自己的具有前景色和背景色的自定义 ToolTip
,然后扩展 JComponent
类(JButton
、JLabel
等都是 JComponent
) 并覆盖其createToolTip()
方法并设置您的自定义 ToolTip
作为 JComponent
的 ToolTip
,像这样:
这是我做的一个例子:
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JToolTip;
import javax.swing.SwingUtilities;
/**
*
* @author David
*/
public class CustomJToolTipTest {
private JFrame frame;
public CustomJToolTipTest() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CustomJToolTipTest();
}
});
}
private void initComponents() {
frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JButton button = new JButton("button") {
//override the JButtons createToolTip method
@Override
public JToolTip createToolTip() {
return (new CustomJToolTip(this));
}
};
button.setToolTipText("I am a button with custom tooltip");
frame.add(button);
frame.pack();
frame.setVisible(true);
}
}
class CustomJToolTip extends JToolTip {
public CustomJToolTip(JComponent component) {
super();
setComponent(component);
setBackground(Color.black);
setForeground(Color.red);
}
}
关于java - 如何仅更改一个组件的工具提示颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13351250/