View Single Post
Old 12-31-2012, 01:47 PM   PM User | #4
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,662
Thanks: 4
Thanked 2,452 Times in 2,421 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
You can't reach inside of the array itself this way. Applying the listener isn't the problem, the referencing it as an array is since the listeners have no idea you are referring to many possible items.
If you want to do it this way, I'd say the easiest approach is to use the setActionCommand on the JButton (also in the loop), and add the array offset to the action command. That can be retrieved within the actionlistener.
PHP Code:
    public static void main(String[] argv)
    {
        
SwingUtilities.invokeLater(new Runnable(){
            @
Override
            
public void run()
            {
                
JFrame jf = new JFrame();
                final 
String[] allWeapons = new String[5];
                
allWeapons[0] = "a";
                
allWeapons[1] = "b";
                
allWeapons[2] = "c";
                
allWeapons[3] = "d";
                
allWeapons[4] = "e";
                
                
ActionListener al = new ActionListener()
                {
                    @
Override
                    
public void actionPerformed(ActionEvent e)
                    {
                        try
                        {
                            
Integer ic Integer.parseInt(e.getActionCommand());
                            
JOptionPane.showMessageDialog(null"Clicked on " allWeapons[ic]);    
                        }
                        catch (
NumberFormatException ex)
                        {
                        }
                    }
                };
                
                for (
int i 0allWeapons.length; ++i)
                {
                    
JButton jb = new JButton(allWeapons[i]);
                    
jb.setActionCommand(Integer.toString(i));
                    
jb.addActionListener(al);
                    
jf.getContentPane().add(jb);
                    
                }
                
jf.setLayout(new GridLayout(15));
                
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                
jf.pack();
                
jf.setVisible(true);
            }
        });
    } 
Like that.
Fou-Lu is offline   Reply With Quote
Users who have thanked Fou-Lu for this post:
Atlan (01-02-2013)