如何爲其中的JMenuBar
和JMenu
對象設置自定義背景顏色?我試過.setBackgroundColor
,它不起作用!更改其內部的JMenuBar和JMenu對象的背景和文字顏色
2
A
回答
7
創建一個擴展JMenuBar
一個新的類:
public class BackgroundMenuBar extends JMenuBar {
Color bgColor=Color.WHITE;
public void setColor(Color color) {
bgColor=color;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(bgColor);
g2d.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
}
}
現在你使用這個類來代替JMenuBar
與setColor()
設置背景顏色。
7
你可能需要更改的菜單項,即不透明度:
JMenuItem item= new JMenuItem("Test");
item.setOpaque(true);
item.setBackground(Color.CYAN);
您也可以實現,全球使用UIManager
,例如:
UIManager.put("MenuItem.background", Color.CYAN);
UIManager.put("MenuItem.opaque", true);
4
最簡單的方法(我能想到的的)是更改UIManager
使用的默認值。這將影響所有的菜單欄和菜單項在這個應用程序...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestMenuBar {
public static void main(String[] args) {
new TestMenuBar();
}
public TestMenuBar() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
UIManager.put("MenuBar.background", Color.RED);
UIManager.put("Menu.background", Color.GREEN);
UIManager.put("MenuItem.background", Color.MAGENTA);
JMenu mnu = new JMenu("Testing");
mnu.add("Menu Item 1");
mnu.add("Menu Item 2");
JMenuBar mb = new JMenuBar();
mb.add(mnu);
mb.add(new JMenu("Other"));
JFrame frame = new JFrame("Test");
frame.setJMenuBar(mb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
0
當我改變礦井只有工作:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
到:
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
否則,顏色保持不變。
0
簡單方法是.setBackground(Color.RED)
和setOpaque(true)
menubar.setBackground(Color.RED); menu.setBackground(Color.yellow); menubar.setOpaque(true); menu.setOpaque(true);
這會給你的選擇的顏色的菜單欄和菜單兩者。
問題可能與LAF有關。使用默認的LAF,您只需設置菜單欄的背景,菜單將繼承此顏色,因爲它是不透明的。發佈證明問題的SSCCE。如果你不知道什麼是SSCCE,你可以隨時搜索網頁。 – camickr 2013-03-27 00:43:49
對,同意Nimbus L&A – mKorbel 2013-03-27 07:35:11