2

我正在做一个任务,我必须创建三行三个盒子,每个盒子里都有一个从 1 到 9 的数字。出于某种原因,这段代码不起作用,它只打印一行,中间有一个 1:

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();
  }
}

我想我的问题是:我可以多次使用同一个 Box 变量来使创建这个 GUI 更容易,还是每次制作同一种盒子时都必须创建不同的变量?

4

2 回答 2

2

由于 aBox只是 another JComponent,因此您必须为组件层次结构中的每个位置创建一个单独的。换句话说,你不能重复使用一个Box,就像你不能重复使用一个一样JTextField

于 2012-08-13T20:33:29.110 回答
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.

于 2012-08-13T20:38:16.737 回答