Search code examples
javauser-interfacejcombobox

Dynamically create ComboBox values Java


I'm new to Java and very new to Java GUI. I have a pretty basic GUI set up with tabbed panes. One basic pane allows the user to add items to a collection. I've begun to set up another pane where I would like to have a ComboBox menu that lists the items in the aforementioned pane (i.e., a list of all the items that have been added) and will allow the user to choose items to delete (via a button)). I've tried to pass the array of items to the "delete" pane and use within a ComboBox in a number of different ways, but since the ComboBox is created in the constructor, it never updates as items are added.

What would be the best way to access this array, as it is updated dynamically from the other pane?


Solution

  • I can think of a few ways to achieve it.

    One of the best ways to pass both panels a reference to common model interface. This would allow the first panel to add items to it and the second panel to be notified when those changes occur and update itself.

    If you don't want to pass this model to both panels on setup, you could use a singlton instead, making the modal globally accessible to both panes. I tend to prefer passing the model to the constructors, as it's easier to change the model implementation this way.

    One possible solution would be to use a DefaultComboBoxModel as the base implementation. This has the ability to allow you to add and remove elements from the model, but would allow you to assign to the combo as it's model very easily. But this will come down to what it is you want to achieve with the collection.

    Another approach would be to attach ChangeListener to JTabbedPane. When the active tab changes, you could inspect the values from the first pane and assign them to the second.

    This is a more coupled then the first, as it assumes the tabbed pane "knows" about the relationship between the two panes (and knows which two panes need to be updated)