<Swing Dev> 6179357: Generics: JList: Constructors & Model
Florian Brunner
fbrunnerlist at gmx.ch
Wed Feb 18 23:47:53 UTC 2009
Well, there is probably no big issue with JList, because the ListModel is immutable.
But when we add generics to JComboBox, which is similar to JList, the situation is a bit more
controversial, because the ComboBoxModel is mutable.
So if we have something like this:
class JComboBox<E>{
ComboBoxModel<? extends E> getModel();
setModel(ComboBoxModel<? extends E>);
}
then something like this is not possible:
JComboBox<Foo> cb = new JComboBox<Foo>(...);
...
Foo foo;
ComboBoxModel<? extends Foo> model = cb.getModel();
model.setSelectedItem(foo); -> compile time error
You would need to do an unchecked (-> not type-safe) cast first:
ComboBoxModel<Foo> model = (ComboBoxModel<Foo>) cb.getModel();
And type-safty is what generics is all about.
-Florian
Am Dienstag, 3. Februar 2009 schrieb Pavel Porvatov:
> Hi Florian,
>
> > ----------------------------------------
> >
> > public JList(ListModel dataModel)
> >
> > {
> >
> > if (dataModel == null) {
> >
> > throw new IllegalArgumentException("dataModel must be non null");
> >
> > }
> >
> > // Register with the ToolTipManager so that tooltips from the
> >
> > // renderer show through.
> >
> > ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
> >
> > toolTipManager.registerComponent(this);
> >
> > layoutOrientation = VERTICAL;
> >
> > this.dataModel = dataModel;
> >
> > selectionModel = createSelectionModel();
> >
> > setAutoscrolls(true);
> >
> > setOpaque(true);
> >
> > updateUI();
> >
> > }
> >
> > --->
> >
> > public JList(ListModel<E> dataModel)
> >
> > {
> >
> > if (dataModel == null) {
> >
> > throw new IllegalArgumentException("dataModel must be non null");
> >
> > }
> >
> > // Register with the ToolTipManager so that tooltips from the
> >
> > // renderer show through.
> >
> > ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
> >
> > toolTipManager.registerComponent(this);
> >
> > layoutOrientation = VERTICAL;
> >
> > this.dataModel = dataModel;
> >
> > selectionModel = createSelectionModel();
> >
> > setAutoscrolls(true);
> >
> > setOpaque(true);
> >
> > updateUI();
> >
> > }
> >
> > We could define the signature also like this:
> >
> > public JList(ListModel<? extends E> dataModel)
> >
> > but then we would have to define the dataModel-field also with:
> >
> > private ListModel<? extends E> dataModel
> >
> > as well as the model-property. I don't think this would be a good idea
> > and thus define the signature as:
> >
> > public JList(ListModel<E> dataModel)
> >
> > What do you think?
>
> Why do you think that "private ListModel<? extends E> dataModel" is not
> a very good idea?
>
> Regards, Pavel
More information about the swing-dev
mailing list