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"));
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"));
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();
}
});
}
}
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
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;
}