0

I have a 4 x 6 grid (24 elements) of dropdown boxes in a GUI that all contain the same dropdown list, but evidently each can be selected to a different value.

Trying to generalise this I want to use an array of JComboBox[4][6], so the straightforward way to declare this before iteratively filling the comboboxes would be something like this:

int nLines = 4;
int nParams = 6;
JComboBox<String>[][] labelFields = new JComboBox[nLines][nParams];

Yet this produces a warning:

Gui.java:40: warning: [unchecked] unchecked conversion
    JComboBox<String>[][] labelFields = new JComboBox[nLines][nParams];

Ignoring the warning and trying to fill the JComboBoxes iteratively at runtime doing something like this blows up with a NullPointerException:

labelFields[0][0].addItem("Some string");

So let's try to make the warning go away, again in the most straightforward way:

JComboBox<String>[][] labelFields = new JComboBox<String>[nLines][nParams];

But, disappointment ensues at compile time:

Gui.java:40: error: generic array creation
    JComboBox<String>[][] labelFields = new JComboBox<String>[nLines][nParams];
                                        ^

What am I missing here and what detours must this tired old mule take to make this work?

Balthasar
  • 1,227
  • 2
  • 13
  • 24
  • Also perhaps this SO question: https://stackoverflow.com/questions/3903196/error-generic-array-creation – markspace Jul 03 '22 at 01:38
  • This is a long-fought over problem, that of trying to make an array of a class that utilizes generics, and the best solution is probably not to do this as doing this fights against how generics have been (poorly) implemented in Java. Consider instead of making a `List>` or even a 2D version: `List>>`. Better still, perhaps your issue would best be solved with a JTable that displays combo boxes. – Hovercraft Full Of Eels Jul 03 '22 at 01:38
  • 1
    @HovercraftFullOfEels You want to see poorly implemented generics, take a look at generic `Protocol`s in Swift - it's completely unusable – MadProgrammer Jul 03 '22 at 01:47
  • @MadProgrammer: yikes!!! `@`Balthasar, please check out [this pastebin](https://pastebin.com/kvQsY2nn) for an example of what I was talking about regarding using a JTable with combo box cell editors. – Hovercraft Full Of Eels Jul 03 '22 at 01:59
  • @MadProgrammer: I'm struggling hard enough as it is to wrap my brain around JavaScript's prototypical inheritance – Hovercraft Full Of Eels Jul 03 '22 at 02:07

0 Answers0