Afaque Hussain Afaque Hussain - 4 days ago 5
Java Question

Dynamic Arraylist of checkboxes in Java Swing

I'm writing a GUI Java program for student registration which will retrieve available classes from database, give the user an option to choose classes and then store this in DB.

What I'm trying to do and have so far achieved partial success, is this - I created a combo box with the available majors (got that from DB), retrieved the available classes for that major and displayed check boxes for these classes.

There are two issues with this code.


  1. After selecting the major from combo box, the check boxes aren't displayed. They appear one by one only when I hover my cursor.

  2. Once I change my major in the combo box, the check boxes are not updated, even though the console in eclipse says check boxes for newly selected major has been created.






ArrayList<JCheckBox> checkBoxes=new ArrayList<JCheckBox>();
//combox action listener below
public void actionPerformed(ActionEvent e)
{
//get all available classes for the selected major
avail_class = new String[count_class];

//get all available class ids
avail_classid = new String[count_class];

JCheckBox checkbox;
int xdim = 75;
for (int i = 0; i < count_class; i++)
{
checkbox = new JCheckBox(avail_classid[i] + "-" + avail_class[i]);
checkbox.setBackground(new Color(0, 255, 255));
checkbox.setBounds(183, xdim, 289, 23);
contentPane.add(checkbox);
checkBoxes.add(checkbox);
checkbox.setEnabled(true);

xdim = xdim + 50;
}
}


EDIT

For my second problem, I called repaint() and it worked. For the first one, I did the following:

if(flag < 0)

//flag will be raised whenever there is a change in the selected major. For ex, from web dev to data analytics

for(int i = 0; i < checkBoxes.size(); i++)
{
checkBoxes.get(i).setVisible(false);
System.out.println("old Checkboxes invisible!" + i);
}

Answer

you need to call repaint and revalidate function to the container that holds your check boxes to redraw it with the new check boxes .

Comments