import javax.swing.JMenuBar;
import java.awt.Color;
import javax.swing.JMenu;
import java.awt.event.KeyEvent;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import java.awt.event.InputEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
public class ChangeMenuItemDemo extends JMenuBar
{
final Color bgColor = new Color(240,240,240);
JMenuItem modelAJMI, modelBJMI, modelCJMI, exitJMI;
ChangeMenuItemDemo()
{
super();
setBackground(bgColor);
//create an ActionListener for all menuItem
MyActionListener myActionListener = new MyActionListener();
//build your firt menu
JMenu fileJM = new JMenu("File");
fileJM.setBackground(bgColor);
fileJM.setMnemonic(KeyEvent.VK_F);
add(fileJM);
//a group of JMenuItems
//model a with index 0
modelAJMI = new JMenuItem("model a");
modelAJMI.setMnemonic(KeyEvent.VK_A);
modelAJMI.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));
modelAJMI.addActionListener(myActionListener);
fileJM.add(modelAJMI);
//model b with index 1
modelBJMI = new JMenuItem("model b");
modelBJMI.setMnemonic(KeyEvent.VK_B);
modelBJMI.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_B, InputEvent.CTRL_MASK));
modelBJMI.addActionListener(myActionListener);
fileJM.add(modelBJMI);
//model c with index 2
modelCJMI = new JMenuItem("model c");
modelCJMI.setMnemonic(KeyEvent.VK_C);
modelCJMI.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));
modelCJMI.addActionListener(myActionListener);
fileJM.add(modelCJMI);
//add separator with index 3
fileJM.addSeparator();
//exit with index 4
exitJMI = new JMenuItem("exit");
exitJMI.addActionListener(myActionListener);
fileJM.add(exitJMI);
}
class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
if(source == modelAJMI)
modelAJMI.setText("MODEL A");
else if(source == modelBJMI)
{
// you can add your code here...
}
else if(source == modelCJMI)
{
// you can add your code here...
}
else if(source == exitJMI)
System.exit(0);
}
}
public static void main(String [] args)
{
JFrame frame = new JFrame("ChangeMenuItemDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(new ChangeMenuItemDemo());
frame.setSize(500, 300);
frame.setVisible(true);
}
}