ActionListener() refer to the same object

88 views Asked by At

I want to create dynamic menu in windowbuilder/java,So I create Vector to hold the JMenuItem, but I am facing problem for how can ActionListener() refer to the same object. Thus, How can I access refer to the Object do the action of ActionListener()?

me code is

        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        JMenu mnNewMenu = new JMenu("File");
        menuBar.add(mnNewMenu);
        mnNewMenu.add(mntmNewMenuItem);
        Vector<JMenuItem> x=new Vector<JMenuItem>();
        for(Integer i=0;i<10;i++)
         {
        x.add(new JMenuItem(i.toString()));
        x.get(i).addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
            System.out.println(this.getText());  //this should refer to the same object x.get(i)
            }
        });
        mnNewMenu.add(x.get(i));
         }
1

There are 1 answers

0
Reimeus On BEST ANSWER

Use getSource to get a reference to the source component

JMenuItem menuItem = (JMenuItem) event.getSource();
String text = menuItem.getText();