i want my app to create jcheckboxes from an input that always changes. I want to create a jtextfield near every checkbox, that will be set enabled, only when his checkbox is pressed.
I managed to create this code:
//Create checkboxes with textfileds
for (int i = 0; i < activeProjects.length; i++) {
projectPanels[i] = new JCheckBox(activeProjects[i]);
projectPanels[i].setSelected(false);
projectPanels[i].setComponentOrientation (ComponentOrientation.RIGHT_TO_LEFT);
projectPanels[i].setAlignmentX(RIGHT_ALIGNMENT);
projectPanels[i].addItemListener(this);
projectStorageNum[i] = new JTextField("");
// projectStorageNum[i].setEnabled(false);
projectStorageNum[i].setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
projectStorageNum[i].setMaximumSize(new Dimension(200,30));
projectStorageNum[i].setMinimumSize(new Dimension(200,30));
projectStorageNum[i].setPreferredSize(new Dimension(200,30));
projectStorageNum[i].setAlignmentX(RIGHT_ALIGNMENT);
tmppnl = new JPanel();
tmppnl.add(projectStorageNum[i]);
tmppnl.add(projectPanels[i]);
checkBoxPanel.add(tmppnl);
}
and this is my state change listener:
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
JCheckBox myBox= (JCheckBox)source;
String bName = myBox.getText();
if (e.getStateChange() == ItemEvent.SELECTED)
{
// enable matching text field.
// add bName to projects list.
}
else
{
//disable matching textfield
// remove bName from list
}
when I access the checkboxes in a dynamic way I don't have access to the second array of textfields. is there any way to link them , or any other idea ?
thanks
Dave.
One thing you could do is use the setName and getName methods of Component to save the index of the JCheckBox.
projectPanels[i].setName(Integer.toString(i));
Then, in your state change listener.
int i = Integer.valueOf(e.getName());
This gives you the index of the JTextField.