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));
}
Use
getSource
to get a reference to the source component