Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a JComboBox model unsing a ListModel. Does it have hidden consecuences?

I use both JList and JComboBox in different places. The content of both change dynamically.

Once a comboBox is created you cant just say comboBox.setModel(String[]), you have to create a new model and then set it to the comboBox.

Same happens with the JList.

Rather than creating my own Jlist and ComboBox just to add a new method called .setNewModel(String[]) i created a static method in my "utility" class that receives a String[] and returns a ListModel.

So i can do this:

someComboBox.setModel((ComboBoxModel)UtilityClass.convetToListModel(aStringArray));

I use the same for the JList.

someList.setModel(UtilityClass.convetToListModel(anotherStringArray));

my question is:

Could the casting of the listModel as a ComboBoxModel have some unexpected consequences? If so, is there anyway to change the entire content of a comboBox without having to transform the ArrayString into a Model?

here is the code of the method:

public static ListModel convertToListModel(String[] nList)
{
    return (new JComboBox(nList).getModel());
}

The program compiles and runs fine, but casting always generates doubts in me, specially complex objects. Yes i know i can extend JComboBox and JList to add a method that does the job but its a lot of extra work. Why the ComboBox and Jlist don't have a update or modify Model than accept a simple array of Strings?

like image 943
rciafardone Avatar asked Dec 27 '25 16:12

rciafardone


1 Answers

How is

someComboBox.setModel((ComboBoxModel)UtilityClass.convetToListModel(aStringArray));

in any way easier to write/simpler/whatever than

someComboBox.setModel(new DefaultComboBoxModel(aStringArray))

all you added is white noise in the form of the Utility method. Plus

  • the implementation of that method is simply ... crazy: you create a JComboBox just for the sake of accessing the model that's internally created by that combo ...
  • you have to exploit implementation to type-cast for usage in a real combo ...

Don't do such wasteful/unnecessary stuff, don't even think of going any detours when there's a simple straightforward manner to reach the same goal

like image 117
kleopatra Avatar answered Dec 30 '25 06:12

kleopatra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!