So I want to create a program that creates a JPanel window with 8 JButtons. instead of repeating the JButtons, I just made an array with all of the JButtons and made a loop to create them. Ever since I made an array however, the constructor will not proceed after the loop finishes. This never happened until I made the JButtons into an array.
public class Gui extends JFrame {
private JButton Subject[] = new JButton[7];
private String SubjNames[] = {"Length", "Mass", "Currency", "Temperature", "Time", "Speed", "Data", "Cooking"};
private int SubjectLocX = 40;
private int SubjectLocY = 50;
public Gui (){
super("Converter");
setLayout(null);
System.out.println("yes");
for (int i = 0; i<8; i++) {
Subject[i] = new JButton(SubjNames[i]);
Subject[i].setLocation(SubjectLocX,SubjectLocY);
Subject[i].setSize(200,50);
add(Subject[i]);
if (i < 3) {
SubjectLocX = 40;
SubjectLocY += 100;
} else if (i == 3) {
SubjectLocY = 50;
} else if (i > 3) {
SubjectLocX = 330;
SubjectLocY += 100;
}
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,500);
setLocation(400,200);
setVisible(true);
}
}
Yes, I imported everything needed and I created an object of the class in a seperate class. It will run, but the constructor will not continue after the loop. If you remove the lines with the array "Subject[i]", the constructor finishes and the window appears, but with the array, it does not. Why??
Maybe because you have a JButton array with 7 elements and you are tring to initialize 8 of them. Change declaration with private JButton Subject[] = new JButton[8]
and you will fix.