相对简单,如何设置 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 m = new MenuBar() {
void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setBackground(Color.yellow);
g2.fillRect(0, 0, getWidth(), getHeight());
}
但没什么
好吧,首先,您所展示的不是JMenuBar
,而是MenuBar
,存在显着差异。尝试使用 aJMenuBar
和 usesetBackground
来改变背景颜色
根据 Vulcan 的反馈更新
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方法中的代码(在旧背景之上)。
更好地用你自己的基于 BasicMenuBarUI 替换菜单栏 UI:
menuBar.setUI ( new BasicMenuBarUI ()
{
public void paint ( Graphics g, JComponent c )
{
g.setColor ( Color.RED );
g.fillRect ( 0, 0, c.getWidth (), c.getHeight () );
}
} );
您还可以为所有菜单栏全局设置该 UI,这样您每次创建菜单栏时就不需要使用特定组件:
UIManager.put ( "MenuBarUI", MyMenuBarUI.class.getCanonicalName () );
这里的 MyMenuBarUI 类是所有菜单栏的特定 UI。