add action listener to "unnamed" JButton

is it possible to add an action listener to an unnamed JButton?

For example, I want to add an action listener to the button i'll add to the panel:

JPanel panel=new JPanel();

panel.add(new JButton("button"));

[324 byte] By [fusspota] at [2007-11-26 20:41:41]
# 1

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class Testing

{

public void buildGUI()

{

JPanel panel=new JPanel();

panel.add(new JButton("dummy"));

panel.add(new JButton("button"));

JFrame f = new JFrame();

f.getContentPane().add(panel);

f.pack();

f.setLocationRelativeTo(null);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

Component[] comp = panel.getComponents();

for(int x = 0, y = comp.length; x < y; x++)

{

if(comp[x] instanceof JButton)

{

if(((JButton)comp[x]).getActionCommand().equals("button"))

{

((JButton)comp[x]).addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

JOptionPane.showMessageDialog(null,"button");

}

});

}

}

}

}

public static void main(String[] args)

{

SwingUtilities.invokeLater(new Runnable(){

public void run(){

new Testing().buildGUI();

}

});

}

}

Michael_Dunna at 2007-7-10 2:00:28 > top of Java-index,Desktop,Core GUI APIs...
# 2
wow! thanks!
fusspota at 2007-7-10 2:00:28 > top of Java-index,Desktop,Core GUI APIs...
# 3
And the code will look much uglier. Why just not create a button in a separate statement?
kirillga at 2007-7-10 2:00:28 > top of Java-index,Desktop,Core GUI APIs...
# 4

Follow-up question (to MichaelDunn or anybody):

can i use the "unnamed" buttons' methods?

example:

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class practice2

{

int x, y;//

Component[] comp;//

public void buildGUI()

{

JPanel panel=new JPanel();

panel.add(new JButton("dummy"));

panel.add(new JButton("button"));

JFrame f = new JFrame();

f.getContentPane().add(panel);

f.pack();

f.setLocationRelativeTo(null);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

comp = panel.getComponents();

for(x = 0, y = comp.length; x < y; x++)

{

if(comp[x] instanceof JButton)

{

if(((JButton)comp[x]).getActionCommand().equals("button"))

{

((JButton)comp[x]).addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

((JButton)comp[x]).setEnabled(false);

}

});

}

}

}

}

public static void main(String[] args)

{

SwingUtilities.invokeLater(new Runnable(){

public void run(){

new practice2().buildGUI();

}

});

}

}

the code above doesn't compile

fusspota at 2007-7-10 2:00:28 > top of Java-index,Desktop,Core GUI APIs...
# 5

if(((JButton)comp[x]).getActionCommand().equals("button"))

{

final JButton btn = (JButton)comp[x];

btn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

btn.setEnabled(false);

}

});

break;

}

Michael_Dunna at 2007-7-10 2:00:28 > top of Java-index,Desktop,Core GUI APIs...