3

as the title states, i need to know how to determine if a menu item was clicked or not, then run the function associated. for instance i have a JMenu with a JMenuItem "exit", which when clicked should run a close form method.

import javax.swing.*;

public class selector_form extends JFrame {


/**
 * 
 */
private static final long serialVersionUID = -5963842156289770842L;

public selector_form(String name)
{
    super.setTitle(name);
    setupComponents(this);
    super.setVisible(true);

}

private void setupComponents(JFrame frame)
{

    JMenuItem file_items = new JMenuItem("Exit");
    JMenuItem config_items = new JMenuItem("Preferences");
    JMenuItem[] machine_items = {new JMenuItem("Refresh"), 
            new JMenuItem("Add Dynamically"), new JMenuItem("Remove Dynamically")
    };
    JMenuItem[] emulator_items = {new JMenuItem("Start Emulator"),
            new JMenuItem("Stop Emulator"), new JMenuItem("Pause Emulator"),
            new JMenuItem("Reset Emulator"), new JMenuItem("Crash Emulator")
    };
    JMenuItem[] memory_items = {new JMenuItem("View Emulator Memory"),
            new JMenuItem("System Cheats"), new JMenuItem("Dump Emulator Memory"),
            new JMenuItem("Edit Specific Address"), 
            new JMenuItem("Show Allocations"), new JMenuItem("Allocate Memory"),
            new JMenuItem("DeAllocate Memory")
    };
    JMenuItem[] cpu_items = {new JMenuItem("Show Host Specs"),
            new JMenuItem("Show Emulator Specs"), 
            new JMenuItem("Enable HyperThreadding")
    };
    JMenuItem[] about_items = {new JMenuItem("Help Contents"), 
            new JMenuItem("About")
    };

    frame.setSize(800, 600);

    JMenuBar jmb = new JMenuBar();
    JMenu jm_a = new JMenu("File");
    JMenu jm_c = new JMenu("Config");
    JMenu jm_d = new JMenu("Machines");
    JMenu jm_e = new JMenu("Emulator");
    JMenu jm_f = new JMenu("Memory");
    JMenu jm_g = new JMenu("CPU");
    JMenu jm_h = new JMenu("About");

    jm_a.add(file_items);
    jm_c.add(config_items);
    for(JMenuItem item : machine_items)
        jm_d.add(item);
    for(JMenuItem item : emulator_items)
        jm_e.add(item);
    for(JMenuItem item : memory_items)
        jm_f.add(item);
    for(JMenuItem item : cpu_items)
        jm_g.add(item);
    for(JMenuItem item : about_items)
        jm_h.add(item);

    jmb.add(jm_a);
    jmb.add(jm_c);
    jmb.add(jm_d);
    jmb.add(jm_e);
    jmb.add(jm_f);
    jmb.add(jm_g);
    jmb.add(jm_h);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

    frame.setJMenuBar(jmb);

}

}
7c00h
  • 91
  • 1
  • 10
  • do you really want to know when it is _clicked_? Typically, you shouldn't care about which user interaction triggers the menu (could be a selection by key, f.i.). And typically, the items are configured by _Action_s which trigger whatever needs to be done, see the tutorial referenced in the swing tag wiki – kleopatra Nov 19 '12 at 13:00
  • what i mean by this, is, say for instance i was making firefox, for example, and i need to know if the user hit the add tab button. this is just an example. – 7c00h Nov 19 '12 at 13:08

3 Answers3

4

Just add an ActionListener to it.

menu_item.addActionListener(this);

and implement the ActionListener interface.

Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91
  • 1
    actually, that's not the best approach (@totymedi as well) - the general rule is to always use the highest abstraction available, which is an Action – kleopatra Nov 19 '12 at 13:11
3

You can do this with an ActionListener. You can create your own ActionListener class.

class MenuActionListener implements ActionListener {
  public void actionPerformed(ActionEvent e) {
    System.out.println("Selected: " + e.getActionCommand());    
  }
}

Than add it to the JMenuItem.

JMenuItem newMenuItem = new JMenuItem("New");
newMenuItem.addActionListener(new MenuActionListener());
totymedli
  • 29,531
  • 22
  • 131
  • 165
0

thanks for all the answers. here is what i did.

i used totymedli's example and wrote a class called MenuActionHelper, which calls a MenuEventHandler speciality class, which passes an ID to a function which calls the function needed.

updated selector-form:

package application;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class selector_form extends JFrame {

public static MenuEventHandler mehandler;
/**
 * 
 */
private static final long serialVersionUID = -5963842156289770842L;

public selector_form(String name)
{
    super.setTitle(name);
    setupComponents(this);
    super.setVisible(true);
    mehandler = new MenuEventHandler(this);

}

private void setupComponents(JFrame frame)
{

    JMenuItem file_items = new JMenuItem("Exit");
    JMenuItem config_items = new JMenuItem("Preferences");
    JMenuItem[] machine_items = {new JMenuItem("Refresh"), 
            new JMenuItem("Add Dynamically"), new JMenuItem("Remove Dynamically")
    };
    JMenuItem[] emulator_items = {new JMenuItem("Start Emulator"),
            new JMenuItem("Stop Emulator"), new JMenuItem("Pause Emulator"),
            new JMenuItem("Reset Emulator"), new JMenuItem("Crash Emulator")
    };
    JMenuItem[] memory_items = {new JMenuItem("View Emulator Memory"),
            new JMenuItem("System Cheats"), new JMenuItem("Dump Emulator Memory"),
            new JMenuItem("Edit Specific Address"), 
            new JMenuItem("Show Allocations"), new JMenuItem("Allocate Memory"),
            new JMenuItem("DeAllocate Memory")
    };
    JMenuItem[] cpu_items = {new JMenuItem("Show Host Specs"),
            new JMenuItem("Show Emulator Specs"), 
            new JMenuItem("Enable HyperThreadding"), 
            new JMenuItem("Show Disassembly in real time")
    };
    JMenuItem[] about_items = {new JMenuItem("Help Contents"), 
            new JMenuItem("About")
    };

    frame.setSize(800, 600);

    JMenuBar jmb = new JMenuBar();
    JMenu jm_a = new JMenu("File");
    JMenu jm_c = new JMenu("Config");
    JMenu jm_d = new JMenu("Machines");
    JMenu jm_e = new JMenu("Emulator");
    JMenu jm_f = new JMenu("Memory");
    JMenu jm_g = new JMenu("CPU");
    JMenu jm_h = new JMenu("About");

    jm_a.add(file_items);
    jm_c.add(config_items);
    for(JMenuItem item : machine_items)
        jm_d.add(item);
    for(JMenuItem item : emulator_items)
        jm_e.add(item);
    for(JMenuItem item : memory_items)
        jm_f.add(item);
    for(JMenuItem item : cpu_items)
        jm_g.add(item);
    for(JMenuItem item : about_items)
        jm_h.add(item);

    jmb.add(jm_a);
    jmb.add(jm_c);
    jmb.add(jm_d);
    jmb.add(jm_e);
    jmb.add(jm_f);
    jmb.add(jm_g);
    jmb.add(jm_h);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

    frame.setJMenuBar(jmb);

    //Menu Action Helpers
    file_items.addActionListener(new MenuActionHelper(1));

}

}

/* EFFECTIVE ACTIONLISTENER
 * 
 * passes an integral argument to MeunEventHandler
 */

class MenuActionHelper implements ActionListener
{

public static int digitalIdentifier;

public MenuActionHelper(int i)
{
    MenuActionHelper.digitalIdentifier = i;
}
@Override
public void actionPerformed(ActionEvent arg0) 
{
    try
    {
        if(!(selector_form.mehandler.parseEvent(MenuActionHelper.digitalIdentifier)))
        {
            throw new Exception("Invalid Menu Event ID Parsed!");
        }
        else return;
    }catch(Exception e)
    {
        e.printStackTrace();
    }

}

}

and the new MenuEventHandler class:

package application;

import javax.swing.JFrame;

public class MenuEventHandler {

/* have a static number which is the max an id can be */
public static final int maxActionId = 1000; //good large number

public static JFrame frame;

public MenuEventHandler(JFrame frame) //import jframe functionality
{
    MenuEventHandler.frame = frame;
}

public boolean parseEvent(int i)
{
    boolean success = false;

    switch(i)
    {
    case 1:
    {
        MenuEventHandler.frame.dispose();
        success = true;
    }
    break;
    }
    return success;
}
}

now if someone clicks on the exit MenuItem, the form closes and the application ends.

7c00h
  • 91
  • 1
  • 10