Sean C
Sean C

Reputation: 43

How can I add a check mark next to a menu item that has been selected?

I have the following code which shows a menu called "Options" and under it are the menu items "AI Mode" and "Player Mode". I just want to know how I can mark each one of these with a check mark when chosen.

package com.sean.breakout.menu;

import javax.swing.*;

public class MenuBar extends JMenuBar {

private static final long serialVersionUID = 1L;

public MenuBar() {
    add(createOptionsMenu());   
}

private JMenu createOptionsMenu() {
    JMenu fileOptions = new JMenu("Options");
    JMenuItem aiMode = new JMenuItem("AI Mode");
    JMenuItem playerMode = new JMenuItem("Player Mode");
    fileOptions.add(aiMode);
    fileOptions.add(playerMode);
    return fileOptions;
}

}

Upvotes: 0

Views: 3499

Answers (1)

deezy
deezy

Reputation: 1480

You can change aiMode and playerMode to JCheckBoxMenuItems for this purpose. For example:

JCheckBoxMenuItem aiMode = new JCheckBoxMenuItem("AI Mode");
fileOptions.add(aiMode);
//same goes for playerMode

Documentation for JCheckBoxMenuItem can be found here.

Edit: Here is another SO post on how to select only one item at a time: JCheckBoxMenuItem only one selected

Upvotes: 3

Related Questions