How to make a JMenu without items execute an event?
Hello, everybody!
I have a JMenu without items. I just want to click on it and to execute some code.
JMenu menuSobre = new JMenu("Sobre");
menuSobre.setMnemonic('S');
menuSobre.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
Sobre.exibir(janela);
}
}
);
JMenuBar menu = new JMenuBar();
menu.add(menuSobre);
setJMenuBar(menu);
Why the action listener is not called? What can I do to click on it and have the code
executed?
Thank you very much.
Use a MenuListener to achieve what you want. See attached sample working code.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class TriggerMenu
{
public static void main(String args[])
{
new TriggerMenuFrame();
}
}
class TriggerMenuFrame extends JFrame implements ActionListener
{
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenu view = new JMenu("View");
JMenu help = new JMenu("Help");
JMenuItem fileOpen = new JMenuItem("Open...");
JSeparator separator = new JSeparator();
JMenuItem fileSaveAs = new JMenuItem("Save As...");
JMenuItem editCut = new JMenuItem("Cut");
JMenuItem editCopy = new JMenuItem("Copy");
JMenuItem editPaste = new JMenuItem("Paste");
JMenuItem helpAbout = new JMenuItem("About...");
TriggerMenuFrame()
{
super();
/* Components should be added to the container's content pane */
Container cp = getContentPane();
/* Add menu items to menus */
file.add(fileOpen);
file.add(separator);
file.add(fileSaveAs);
edit.add(editCut);
edit.add(editCopy);
edit.add(editPaste);
help.add(helpAbout);
/* Add menus to menubar */
mb.add(file);
mb.add(edit);
mb.add(view);
mb.add(help);
/* Set menubar */
setJMenuBar(mb);
/* Add the action listeners */
fileOpen.addActionListener(this);
fileSaveAs.addActionListener(this);
editCut.addActionListener(this);
editCopy.addActionListener(this);
editPaste.addActionListener(this);
helpAbout.addActionListener(this);
/* Add menu listener */
view.addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent evt) {
}
public void menuSelected(MenuEvent evt) {
System.out.println("Menu has been selected!");
}
public void menuDeselected(MenuEvent evt) {
}
});
/* Add the window listener */
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
dispose(); System.exit(0);
}
});
/* Size the frame */
setSize(200,200);
/* Center the frame */
Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle frameDim = getBounds();
setLocation((screenDim.width - frameDim.width) / 2,(screenDim.height - frameDim.height) / 2);
/* Show the frame */
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
Object obj = evt.getSource();
if (obj == fileOpen);
else if (obj == fileSaveAs);
else if (obj == editCut);
else if (obj == editCopy);
else if (obj == editPaste);
else if (obj == helpAbout);
}
}