And*_*der 5 java swing tooltip
如何仅为一个组件更改工具提示的颜色?
我知道您可以执行以下操作来更改工具提示颜色:
UIManager.put("ToolTip.background", new ColorUIResource(255, 247, 200));
Run Code Online (Sandbox Code Playgroud)
但这会改变所有组件的工具提示背景,而不仅仅是一个.
任何简单的解决方
+1给@MadProgrammer和@Reimeus他们的建议和例子.
这些都是正确的.
加上...
没有默认方法可以做到这一点.你必须扩展ToolTip类,创建自己的自定义ToolTip用前景色和背景色,然后再扩展JComponent的类(JButton,JLabel,等都是JComponentS)和覆盖其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);
}
}
Run Code Online (Sandbox Code Playgroud)
没有标准的方法可以做到这一点,但你可以覆盖JComponent.createToolTip().这是一个按钮示例:
MyButton testButton = new MyButton("Move Mouse Over Button");
testButton.setToolTipText("Some text");
class MyButton extends JButton {
public MyButton(String text) {
super(text);
}
@Override
public JToolTip createToolTip() {
return (new MyCustomToolTip(this));
}
}
class MyCustomToolTip extends JToolTip {
public MyCustomToolTip(JComponent component) {
super();
setComponent(component);
setBackground(Color.black);
setForeground(Color.red);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3649 次 |
| 最近记录: |