I am working on a project and made good progress until I stumbled upon an unexpected exception. It is caused by intiatiating a JMenuItem and somewhat surprising, as I did similar things before. I found out that the class (class2) works ok, if it is not a subclass of JMenuItem (class4). I also found a workaround (class3), but I still would like to know, what I am doing wrong. I searched for an answer, but did not come up with an answer, probably because of poor search terms. Anyone any ideas?
import javax.swing.JMenuItem;
class class1 {
public static void main(String[] f) {
System.err.println(new class3(0));
System.err.println(new class3(1));
System.err.println(new class4(0));
new class2(1);
}
}
class class2 extends JMenuItem {
static String[] a;
int b;
{
a = new String[2];
a[0] = "c";
a[1] = "d";
}
public class2(int e) {
super();
b = e;
}
public String getText() {
return a[b];
}
public String toString() {
return class2.class + ": " + b + ", " + getText();
}
}
class class3 extends JMenuItem {
static String[] a;
int b;
{
a = new String[2];
a[0] = "c";
a[1] = "d";
}
public class3(int e) {
super();
b = e;
}
public String getText() {
if ( b == 0 ) return "g";
return a[b];
}
public String toString() {
return class3.class + ": " + b + ", " + getText();
}
}
class class4 {
static String[] a;
int b;
{
a = new String[2];
a[0] = "c";
a[1] = "d";
}
public class4(int e) {
super();
b = e;
}
public String getText() {
return a[b];
}
public String toString() {
return class4.class + ": " + b + ", " + getText();
}
}
And this happens, when I execute the class:
$ javac class1.java
$ java -showversion class1
java version "1.8.0_73"
Java(TM) SE Runtime Environment (build 1.8.0_73-b02)
Java HotSpot(TM) 64-Bit Server VM (build 25.73-b02, mixed mode)
class class3: 0, g
class class3: 1, d
class class4: 0, c
Exception in thread "main" java.lang.NullPointerException
at class2.getText(class1.java:29)
at javax.swing.AbstractButton.setModel(AbstractButton.java:1779)
at javax.swing.JMenuItem.setModel(JMenuItem.java:173)
at javax.swing.JMenuItem.<init>(JMenuItem.java:150)
at javax.swing.JMenuItem.<init>(JMenuItem.java:110)
at class2.<init>(class1.java:24)
at class1.main(class1.java:8)