Skip to main content
  1. About
  2. For Teams
Asked
Modified 13 years ago
Viewed 205 times
2

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?

2
  • 1
    What is numIncrement? You haven't defined it, does it come from one of the imports?
    TheZ
    –  TheZ
    2012-08-13 20:37:48 +00:00
    Commented Aug 13, 2012 at 20:37
  • Sorry, I do have it in there, I managed to not write it in because I was copypasting around my commented out code attempts.
    kristinalustig
    –  kristinalustig
    2012-08-13 20:42:05 +00:00
    Commented Aug 13, 2012 at 20:42

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Since a Box is just another JComponent, you must create a separate one for each place in the component hierarchy. In other words, you can't reuse one Box just like you can't reuse one JTextField.

2 Comments

Thanks for your help! That makes this layout long and tedious. :)
Not if you use a factory method. edit: which, in your situation, would be overkill.

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.