设置JMenuBar的背景颜色?
比较直接,我怎么设置JMenuBar的背景颜色?设置JMenuBar的背景颜色?
香港专业教育学院的尝试:
MenuBar m = new MenuBar() {
void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setBackground(Color.yellow);
g2.fillRect(0, 0, getWidth(), getHeight());
}
但没什么
嗯,首先,你已经证明不是JMenuBar
,它的MenuBar
,有一个显著的差异。尝试使用JMenuBar
和使用setBackground
改变背景颜色
从反馈更新从火神
好了,在情况setBackground
不工作,这会;)
public class MyMenuBar extends JMenuBar {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
}
}
使用MadProgrammer的方法,您将获得菜单栏背景两次绘制 - 一次通过UI(例如,可能是Windows上的渐变,需要花费一些时间绘制),一次通过您的代码在paintComponent方法(在旧背景之上)。
menuBar.setUI (new BasicMenuBarUI()
{
public void paint (Graphics g, JComponent c)
{
g.setColor (Color.RED);
g.fillRect (0, 0, c.getWidth(), c.getHeight());
}
});
您还可以设置UI全球范围内为所有的菜单栏,使您无需使用特定组件每次创建菜单栏时间:
更好地自己一个基于BasicMenuBarUI更换菜单栏UI :
UIManager.put ("MenuBarUI", MyMenuBarUI.class.getCanonicalName());
这里的MyMenuBarUI类是您所有菜单栏的特定UI。
wooohooo直到现在我看到了Xxx.class。getCanonicalName()第二次,伟大的设计+1 – mKorbel 2012-08-10 16:10:24
@mKorbel谢谢,我真的不明白为什么大多数开发人员对类名进行硬编码(即使它们不会被改变)。 – 2012-08-10 20:53:21
我试过你的第二种方法,但不知何故没有任何效果。我应该在哪里寻找问题? – Czechnology 2013-08-04 11:44:11
JMenuBar#setBackground不设置JMenuBar的背景颜色。 – Vulcan 2012-08-09 23:22:32
@Vulcan很好,你知道些什么,每天都在学点东西:) – MadProgrammer 2012-08-09 23:25:00
@Vulcan错了,它确实设置了颜色! – Primm 2012-08-09 23:26:53