Search code examples
javaswingjcheckboxbuttongroup

Handling large number of Swing components


I'm doing a favor for an engineer friend by making him a program that helps him with the scheduling of his factory's production. Each type of product is broken down to a set of steps (they share a lot of them, but there are a few differences).

The programming issue:

Each time a new production process is registered I display a number of checkboxes representing the before mentioned steps. He can choose which steps he needs added for this particular product. If he checks a checkbox, two (or more) textfields appear where he can add additional information (starting date, duration, comments, etc...). My problem is that this is a lot of individual components and I am unsure how to handle them. Since I will need to have access to all of them at some point (the checkboxes to see if that step is needed and all the textfields for the data) I was thinking of having them all as fields, but that doesn't feel right...

Another approach could be to make a container class that groups the textfields together with the checkbox. Something like this:

ArrayList<MyComponentGroup> group;
for (MyComponentGroup cg : group) {
    if (cg.getCheckBox().isSelected()) {
        //access and read the data from all the textfields in this object
    }
}

What is the Java programming convention or the most commonly used method to handle this situation?


Solution

  • One approach is to consistently give each JComponent a unique name. Use something hierarchical to fit the complex process, like "Whites.Rinsecycle.enableCB". For completeness, store this String as a clientProperty in the JComponent. Then you can use that as a key in a large Map to access all the components.

    Maybe not the most "elegant" (I'd tend to go with a hierarchy of JPanels with relevant fields) but for a slightly quick and dirty, moderate sized project this is reasonable.