I am trying to figure out how to have an action listener on a JButton that I created from an arrayList of JButtons.
Here is the arraylist of buttons:
public static ArrayList<JButton> myTests;
public static ArrayList<JButton> selectedTests;
Here is the logic setting them up:
public Devices(String[] testList, String title2)
{
myTests = createTestList(testList);
selectedTests = new ArrayList<JButton>();
checkedSerialNo = new ArrayList();
int numCols = 2;
//Create a GridLayout manager with
//four rows and one column
setLayout(new GridLayout(((myTests.size() / numCols) + 1), numCols));
//Add a border around the panel
setBorder(BorderFactory.createTitledBorder(title2));
for(JButton jcb2 : myTests)
{
this.add(jcb2);
}
}
private ArrayList<JButton> createTestList(String[] testList)
{
String[] tests = testList;
ArrayList<JButton> myTestList = new ArrayList<JButton>();
for(String t : tests)
{
myTestList.add(new JButton(t));
}
for(JButton jcb2 : myTestList)
{
jcb2.addItemListener(this);
}
return myTestList;
}
@Override
public void itemStateChanged(ItemEvent ie)
{
if(((JButton)ie.getSource()).isSelected())
{
selectedTests.add((JButton) ie.getSource());
}
}
public ArrayList<JButton> getSelectedTests()
{
return selectedTests;
}
What I don't know is how to make the actionListner or onClickListener for the generated buttons in the array list.
Well the easiest way would be to create an internal private class.
private class MyTestListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// stuff that should happen
}
}
private class SelectedTestListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// stuff that should happen
}
}
The private classes need to be in the same java file (where you work with your ArrayLists). Once you created the classes you just have to add the action Listener.
MyTestListener handler = new MyTestListener();
//Inside the for-each
button.addActionListener(myListener);
If you only need 1 Listener (for one button type that is; like the itemStateListener) just define one private class with a fitting name and add it to the button in the foreach with the function mentioned above .addActionListener
Have a nice day