Reputation: 61
I've created a menu in the menu bar, in which I'd like to create a JCheckBoxMenuItem
to set a condition for highlighting remaining menu items.
Something like the following pseudo-code:
if login(true)
then highlight remaining menuitems
else
un-highlight the menuitems
Upvotes: 0
Views: 2381
Reputation: 39164
I think for highlighting you mean enable/disable a JMenuItem. That's possible.
Use setEnabled:
JMenuItem item;
item.setEnabled(false); //to disable
Like suggested by kleopatra, the best way of doing that is to implement your own action for each JMenuItem, and let your action to enable/disable the button accordingly to the state:
For example:
public class AMenuAction extends AbstractAction {
@override
public void actionPerformed(ActionEvent e) {
//implement your action behavior here
}
}
Then construct your JMenuItem with such action:
AMenuAction afterLoginAction = new AMenuAction();
JMenuItem item = new JMenuItem(afterLoginAction );
When the user logged in/out call setEnabled method on the desired actions.
void Login()
{
afterLoginAction.setEnabled(true);
}
Upvotes: 5
Reputation: 1
Create a JCheckBoxMenuItem
as userlogin menu item
JCheckBoxMenuItem jCheckBoxMenuItem = new JCheckBoxMenuItem();
then
add action listener to it
//unhighlite other menu items before login
jMenuFileOpen.setEnabled(false);
//...
jCheckBoxMenuItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (login(true)){
jCheckBoxMenuItem.setSelected(true);
//highlite other menu items
jMenuFileOpen.setEnabled(true);
//...
} else {
jCheckBoxMenuItem.setSelected(false);
//unhighlite other menu items
jMenuFileOpen.setEnabled(false);
//...
}
}
});
once login(true)
is successful the checkbox is checked on menu and other menu items are enabled.
Upvotes: 2
Reputation: 36611
Enabling and disabling menu items is done in the same way as for any other JComponent
by using the setEnabled( boolean )
method
Upvotes: 4