0
JComboBox[] ChooseType = new JComboBox[a];
    JRadioButton[] Primary = new JRadioButton[a];
    ButtonGroup group = new ButtonGroup();
    for (int b = 0; b < a; b++) {
        ChooseType[b] = new JComboBox(Types);
        Primary[b] = new JRadioButton();
        group.add(Primary[b]);
        Primary[b].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ChooseType[b].setSelectedIndex(8);//Error here
            }
        });
    }

I already tried this:

final JComboBox[] ChooseType = new JComboBox[a];

I tried also to create a inner class and a method, so I dont have to deal directly with the JComboBox inside the actionPerformed. Can someone tell me how to fix it?

  • 1
    Did you look at any of the numerous duplicates with the exact same problem? – tnw May 31 '17 at 14:57
  • 1
    Possible duplicate of [Problems with local variable scope. How to solve it?](https://stackoverflow.com/questions/25894509/problems-with-local-variable-scope-how-to-solve-it) – Frakcool May 31 '17 at 14:58

2 Answers2

1

The problem is with the b variable. You can use a temporary variable:

for (int b = 0; b < a; b++) {
  int b0 = b;
  chooseType[b] = new JComboBox(Types);
  //...
  chooseType[b0].setSelectedIndex(8);//Error here

ps: I've changed the capitalisation of the variable to match Java's conventions.

assylias
  • 321,522
  • 82
  • 660
  • 783
0

To simply put it in code:

    JComboBox[] ChooseType = new JComboBox[a];
    JRadioButton[] Primary = new JRadioButton[a];
    ButtonGroup group = new ButtonGroup();
    for (int b = 0; b < a; b++) {
        //This is the item that's not final
        ChooseType[b] = new JComboBox(Types);
        Primary[b] = new JRadioButton();
        group.add(Primary[b]);
        final JComboBox forListener = ChooseType[b];
        Primary[b].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                forListener.setSelectedIndex(8);//Fixed.
            }
        });
    }
Jan
  • 13,738
  • 3
  • 30
  • 55