我有一个菜单,我想在点击它时更改它。
这是我的代码:
violatorMenu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
violatorMenu.setForeground(new java.awt.Color(255, 255, 255));
violatorMenu.setBackground(new java.awt.Color(183, 28, 28));
}
@Override
public void menuDeselected(MenuEvent e) {
}
@Override
public void menuCanceled(MenuEvent e) {
}
});
此代码不会更改默认颜色。
有什么想法吗?感谢
答案 0 :(得分:0)
尝试violatorMenu.setOpaque(true)。其余代码似乎工作正常。这是一个例子:
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
public class MenuExample extends JFrame {
private void createAndShowGUI() {
/** the main frame */
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar mb = new JMenuBar();
setJMenuBar(mb);
JMenu violatorMenu = new JMenu("A menu");
JMenuItem mi = new JMenuItem("A menu item");
violatorMenu.add(mi);
violatorMenu.setOpaque(true);
mb.add(violatorMenu);
violatorMenu.addMenuListener(new MenuListener() {
@Override
public void menuSelected(MenuEvent e) {
violatorMenu.setForeground(new java.awt.Color(255, 255, 255));
violatorMenu.setBackground(new java.awt.Color(183, 28, 28));
}
@Override
public void menuDeselected(MenuEvent e) {
}
@Override
public void menuCanceled(MenuEvent e) {
}
});
/** show the frame to the user */
pack();
setVisible(true);
}
public static void main(String[] args) {
final MenuExample frame = new MenuExample();
/** schedule for the event dispatcher */
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.createAndShowGUI();
}
});
}
}