This question already has an answer here:
I made a JPanel Child which contains a couple of radio buttons in it. Whenever a radio button is clicked i want an ActionEvent to be generated from the Child also. This action event should "contain" a reference to the button which actually generated an event.
This Child will be used as a component inside another JPanel Parent which will listen to the events from the Child, instead of listening to the individual radio buttons.
How can I do this ?
Code so far -
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class RadioListener extends JPanel implements ActionListener{
public static final String id = "id";
public RadioListener(){
for(int i = 1; i < 5; i++){
JRadioButton jrb = new JRadioButton(i + "", false);
jrb.putClientProperty(id, i);
this.add(jrb);
jrb.addActionListener(this);
}
}
public void actionPerformed(ActionEvent e){
JRadioButton jrb = (JRadioButton) e.getSource();
Integer id = (Integer) jrb.getClientProperty(RadioListener.id);
System.out.println("id " + id);
}
public static void main(String[]args){
JFrame frame = new JFrame("Radio buttons");
frame.getContentPane().setLayout(new FlowLayout());
frame.setSize(400, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new RadioListener());
frame.setVisible(true);
}
}
To go MadProgrammer's recommendations (1+) one step further, you could use Swing Components intrinsic PropertyChangeSupport for this purpose:
Is this solution good enough ?
I'd recommend providing the ability for the component to act as a proxy for other interested parties to register interest.
This means you don't need to expose methods/components that other components shouldn't be calling or have access to.
You should also make use of inner classes for listeners, as they will prevent the exposure of other methods that others shouldn't have access to