Pregunta

So I have an interface, it's got a few constant integers declared and I can access these in any class which implements said interface.

I just declared an array of constant strings in the interface, and I tried to access it, resulting in a null pointer expression, my array is declared like so:

public static final String[] STRINGS = {"bla","bla","bla","bla", "bla", "bla"};

In the test program, the following line returns a NullPointerException:

System.out.println(STRINGS[1]);

So, my question: Is there any problem here, or can you only work with integer constants in an interface?

public class MyFrame extends JFrame implements MyInterface {
....
....
private static JCheckBox[] checkBoxes = new JCheckBox[NUMBER];
....
....
int counter = 0;
        for (JCheckBox box : checkBoxes) {
            box.setText(STRINGS[counter]);
            box.setSelected(false);
            checkBoxPane.add(box);
            counter++;
        }

 ....

The above code shows the test class, NUMBER and STRINGS are declared in MyInterface, I've changed the names for simplicity.

Thanks in advance.

¿Fue útil?

Solución

Elements in an Object array are null by default. Ensure that each JCheckBox is initialized before attempting to invoke a method on the component

for (int i=0; i < checkBoxes.length; i++) {
    checkBoxes[i] = new JCheckBox();
}

Otros consejos

This woks perfectly ok.

public interface Trail {
    public static final String[] STRINGS = {"bla","bla","bla","bla", "bla", "bla"};
}

Implementation

public class X implements Trail{
    public void get() {
        System.out.println(STRINGS[1]);
    }
}

public class TEstMain {
public static void main(String[] args) {

    X x = new X();
    x.get();
}

Output:

bla
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top