Search code examples
javaarraysbooleangetter-setter

Error: The type of the expression must be an array type but it resolved to boolean


I have 6 Buttons and 6 booleans, the Actionhandler should make the boolean, that is for its button, true if it is clicked. To make it easier I made a boolean[] array, but the setter function gives the error:

"The type of the expression must be an array type but it resolved to boolean" ;

What do I need to set in the setter in ActionListener?

I tried:

  • Var.setKo(true);
  • Var.setKo(true[i]);
  • Var.setKo(boolean[i] true);
  • and more


        public class Gui {

    static JButton ko[] = new JButton[6];

    public Gui() {

        int y=0;
        for (int i = 0; i < ko.length; i++) {
            ko[i] = new JButton();
            ko[i].addActionListener(new ActionHandler());
            ko[i].setBorder(bor);
            if(i==0||i==2||i==4) {
                ko[i].setBounds(650, 200+60*y, 250, 30);
            }else {
                ko[i].setBounds(950, 200+60*y, 250, 30);
                y++;
            }
            jfMenu.add(ko[i]);

        }
    }

    public static JButton[] getKo() {
        return ko;
    }

    public static void setKo(JButton[] ko) {
        Gui.ko = ko;
    }


}

public void actionPerformed(ActionEvent e) {

    for (int i = 0; i < Var.getKo().length; i++) {
        if(e.getSource() == Var.getKo()) {
            Var.setKo(true[i]);
        }else {
            Var.getKo()[i] = false;
        }
    }

}

public class Var {

    static boolean ko[] = new boolean[6];

    public Var() {

        for (int i = 0; i < ko.length; i++) {
            ko[i] = false;
        }

    }
    public static boolean[] getKo() {
        return ko;
    }

    public static void setKo(boolean[] ko) {
        Var.ko = ko;
    }
}



Solution

  • You do not need to use the setter here, your array exists, it has initialized, so no need it for it to be set again.

    What you need instead is to change the value of some of its indexes. And that can be done by using the getter, to get the reference to the array, and then select the correct index and assign it a value.

    Like hereunder

    public void actionPerformed(ActionEvent e) {
        for (int i = 0; i < Var.getKo().length; i++) {
            Var.getKo()[i] = e.getSource() == Var.getKo();
        }
    }