Forums Register Login

addActionListener problem

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
hmmm.. is this a bug.. i can see some application menu have their exit with the main menu bar..

anyway. will do that..

thanks
+Pie Number of slices to send: Send
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.
It's a beautiful day in this neighborhood - Fred Rogers. Tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1412 times.
Similar Threads
JTextArea append() not working?
how to enable/disable this item?
Adding JMenuBar, after user Authentication.. Please Help
adding an InternalFrameListener to a JMenu Item
Adding Components in to JInternalFrame
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 01:11:04.