I’m working on an assignment where I have to create three rows of three boxes, each with a number from 1-9 in it. For some reason, this code isn’t working, it only prints one row with a 1 in the center:
import javax.swing.*;
import java.awt.*;
public class PracticeTwo extends JPanel {
private JFrame mainFrame = new JFrame("");
private Box bigBox = Box.createVerticalBox();
private Box smallBox = Box.createHorizontalBox();
private Box numBox = Box.createVerticalBox();
public void makeGui () {
mainFrame.add(bigBox);
bigBox.setAlignmentX(Component.LEFT_ALIGNMENT);
while (num < 10) {
bigBox.add(smallBox);
smallBox.add(numBox);
numBox.add(numIncrement);
smallBox.add(numBox);
numBox.add(numIncrement);
smallBox.add(numBox);
numBox.add(numIncrement);
num++;
}
mainFrame.setVisible(true);
mainFrame.pack();
}
}
I suppose my question is: can I use the same Box variable more than once to make creating this GUI easier, or do I have to create different variables for each time I make the same kind of box?
Variables are used to hold references to object instances so that you can access these instances later when needed. Using variables isn’t the only way you can keep these references handy. Another way is via data structures. Some examples of data structures are: arrays, trees, lists, tables, etc. I guess at this point in your course you may not have yet learned about how to use data structures, so having to define multiple variables is fine for now. In real code, you wouldn’t be doing this.