I made a new project with just the code, that contains the error:
package benutzerschnittstelle;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
public class versuch extends JFrame {
private static JPanel contentPane;
static JCheckBox[] CheckBox;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
versuch frame = new versuch();
frame.setVisible(true);
for (int x = 0; x < 3; x++) {
CheckBox = new JCheckBox[3];
CheckBox[x] = new JCheckBox("Prüfungsfach");
CheckBox[x].setBounds(180, (60 + (25 * x)), 120, 21);
contentPane.add(CheckBox[x]);
}
for (int x = 0; x < 3; x++) {
try {
System.out.println("checkbox " + x
+ " : " + CheckBox[x].isSelected());
} catch (Exception e) {
System.out.println("error at checkbox " + x
+ " : " + e.getLocalizedMessage());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public versuch() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
}
}
Since the checkboxes get checked before I even have the opportunity to select them, the output should be:
checkbox 0: false
checkbox 1: false
checkbox 2: false
but the output is:
error at checkbox 0 : Cannot invoke "javax.swing.JCheckBox.isSelected()" because "benutzerschnittstelle.versuch.CheckBoxPruefungsfach[x]" is null
error at checkbox 1 : Cannot invoke "javax.swing.JCheckBox.isSelected()" because "benutzerschnittstelle.versuch.CheckBoxPruefungsfach[x]" is null
checkbox 2 : false
If I vary the length of the array, the last checkbox always works as intended and the rest causes errors... why is that? And how do I fix it?