Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

addActionListener problem

 
Cyrus Serrano
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello guys,

ive used a JMenu object and cant find the problem when i tried to implement or apply an addActionListener on it..

//insert a menu
//Where the GUI is created:
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;


//Create the menu bar.
menuBar = new JMenuBar();

//Build the first menu. Settings Menu
menu = new JMenu("Settings");
menu.setMnemonic(KeyEvent.VK_S);
menu.getAccessibleContext().setAccessibleDescription("Clock Settings");
menuBar.add(menu);

//Date and Time Menu
menuItem = new JMenuItem("Date and Time",KeyEvent.VK_D);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.addActionListener(this);
menuItem.setActionCommand("Date and Time");
menu.add(menuItem);

//set a separator
menu.addSeparator();

//Alarm Menu
menuItem = new JMenuItem("Alarm", KeyEvent.VK_A);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
menuItem.addActionListener(this);
menuItem.setActionCommand("Alarm");
menu.add(menuItem);



//Build the second menu. Exit Menu
menu = new JMenu("Exit");
menu.setMnemonic(KeyEvent.VK_X);
menu.addActionListener(this);
menu.setActionCommand("Exit");
menuBar.add(menu);



when i tried to click on the Exit button, nothing works..

public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Date and Time")){
System.out.println("Date");
}
else if(ae.getActionCommand().equals("Alarm")){
System.out.println("Alarm");
}
else if(ae.getActionCommand().equals("Exit")){
System.out.println("Exit");
}

}

ive also done this.. i've used the println methods just to see if it works.

thanks
 
Craig Wood
Ranch Hand
Pie
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ActionListeners usually don't work too well on JMenus. Try adding a JMenuItem to a menu and adding the ActionListener to it for the exit. Many apps have the exit item under a file menu.
 
Cyrus Serrano
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hmmm.. is this a bug.. i can see some application menu have their exit with the main menu bar..

anyway. will do that..

thanks
 
Craig Wood
Ranch Hand
Pie
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i can see some application menu have their exit with the main menu bar
It's been quite a while since I tried to do this. If you have seen it done there must be a way; I could have missed something.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic