Создайте JPanel с GridBagLayout и JPanels в каждом столбце - PullRequest
0 голосов
/ 16 декабря 2011

Я пытаюсь создать JPanel с GridBagLayout и панелями в каждом столбце. Но когда я запускаю программу, я всегда получаю только одну панель в сетке, хотя у меня есть цикл для создания панелей 10X10.

ColumnPanel

public class BoardColumnPanel extends JPanel {

public BoardColumnPanel() {
    this.setBackground(Color.GRAY);
    this.setSize(48, 48);
}
}

Вид сетки

public class BoardPanel extends JPanel {

private GridBagLayout layout;

public BoardPanel() {
    initBoardPanel();
}

private void initBoardPanel() {
    layout = new GridBagLayout();
    this.setLayout(layout);
    GridBagConstraints gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
    // fill grid
    BoardColumnPanel column;
    for (int row=0;row<10;row++) {
        for (int col=0; col < 10; col++) {
            column = new BoardColumnPanel();
            gridBagConstraints.gridx = col;
            gridBagConstraints.gridy = row;
            gridBagConstraints.ipadx = 5;
            gridBagConstraints.ipady = 5;
            layout.setConstraints(column,gridBagConstraints);
            this.add(column);
        }
    }

}
}

Ответы [ 3 ]

2 голосов
/ 16 декабря 2011

Ваш код в порядке.Давайте изменим цвет фона BoardColumnPanel:

public class BoardColumnPanel extends JPanel {

  public BoardColumnPanel(int i) {

        this.setBackground(new Color(10 * i, 10 * i, 10 * i));
        this.setSize(48, 48);
    }
}

и инициализируем его другим оттенком серого:

public class BoardPanel extends JPanel {

  private GridBagLayout layout;

  public BoardPanel() {

    initBoardPanel();
  }

  private void initBoardPanel() {

    layout = new GridBagLayout();
    this.setLayout(layout);
    GridBagConstraints gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
    // fill grid
    BoardColumnPanel column;
    for (int row = 0; row < 10; row++) {
      for (int col = 0; col < 10; col++) {
        column = new BoardColumnPanel(row + col);
        gridBagConstraints.gridx = col;
        gridBagConstraints.gridy = row;
        gridBagConstraints.ipadx = 5;
        gridBagConstraints.ipady = 5;
        layout.setConstraints(column, gridBagConstraints);
        this.add(column);
      }
    }

  }

  public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {

      @Override
      public void run() {

        JFrame f = new JFrame();

        f.getContentPane().add(new BoardPanel());

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
      }
    });
  }
}
2 голосов
/ 16 декабря 2011

Я бы предложил использовать GridLayout , обратите внимание, используя этот LayoutManager каждые JComponents будут иметь одинаковый размер на экране,

0 голосов
/ 16 декабря 2011

Я не совсем уверен, но я бы сказал, что GridBagConstraints gridBagConstraints = new GridBagConstraints ();должно быть внутри для циклов.В противном случае вы постоянно устанавливаете gridx / gridy для одного и того же ограничения.

...