我有一个带有JMenuBar和JMenu的JFrame。在曾经的JMenu中,有几个JMenuItem。我只想向这些JMenuItem添加一个侦听器,所以当我单击其中一个时,会发生某些情况。
代码是:

public class FinestraOrario extends JFrame
{

private int semester;
private DBConnection connection = new DBConnection();
private Container c = this.getContentPane();
private JMenu subjMnu = new JMenu("Insegnamento");
private JMenu classMnu = new JMenu("Aula");
private JMenu profMnu = new JMenu("Docente");

    public FinestraOrario(int i)
    {
        semester = i;

        //Define menus
        JMenuBar bar = new JMenuBar();
        JMenu choice = new JMenu("Visualizza Orario per..");

        //Define frame features
        this.setSize(1150,650);
        this.setLocationRelativeTo(null);
        this.setJMenuBar(bar);

        //Add JMenu
        bar.add(choice);
        choice.add(classMnu);
        choice.add(subjMnu);
        choice.add(profMnu);

        //populate Menus
        populateMenu();


    private void populateMenu ()
    {

        //data from database which populate the JMenu as JmenuItem
        ArrayList<String[]> subjctesAndClasses= connection.getSemesterData(semester, "");

        ArrayList<String[]> teachers = connection.getSemesterData(semester, "keep theachers");


        Iterator<String[]> i=subjctesAndClasses.iterator();
        Iterator<String[]> j=teachers.iterator();

        Set<String> set1  = new HashSet<String>();
        Set<String> set2  = new HashSet<String>();
        Set<String> set3  = new HashSet<String>();


                while(i.hasNext())      //check values
                {
                    String[] value=i.next();
                    String subject = value[1];  //value contains at subjects at index 1 and classes at index 2
                    String class=value[2];
                    set1.add(subject);          //erase duplicate
                    set2.add(class);
                }

        //getting value without duplicates
        for (String s: set1)
        {
            JMenuItem item = new JMenuItem(s);
            subjMnu.add(item);
        }

        for (String s: set2)
        {
            JMenuItem item = new JMenuItem(s);
            classMnu.add(item);

        }

                while(j.hasNext())          //idem for teacher
                {
                    String[] value=j.next();
                    String teacher = value[0];
                    set3.add(teacher);
                }

        for (String s: set3)
        {profMnu.add(new JMenuItem(s));}

    }
}


如何将侦听器添加到每个JMenuItem?

最佳答案

JMenuItem item = new之后添加以下内容

 item.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
        {

        }
    });

关于java - 将监听器添加到JFrame中的JMenuItem,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18867149/

10-10 22:57