将面板放入面板Java GUI中

时间:2019-03-16 18:43:33

标签: java swing user-interface panel

我正在尝试制作一个GUI,其中三个面板彼此相邻。然后,我想在第一个面板中放置一个5 X 2面板的网格。我设法创建了两个ttop,但似乎无法在其中放置额外的面板。任何帮助将非常感激!

import java.awt.*;
import javax.swing.*;
import javax.swing.JPanel.*;
import java.awt.Color.*;
/**
 * Write a description of class SimpleFrame here.
 *
 * @author OFJ2
 * @version 
 */
public class Game extends JFrame
{
private final int ROWS = 5;
private final int COLS = 2;
private final int GAP = 2;
private final int NUM = ROWS * COLS;
private int x;
private JPanel leftPanel = new JPanel(new GridLayout(ROWS,COLS, GAP,GAP));
private JPanel [] gridPanel = new JPanel[NUM];
private JPanel middlePanel = new JPanel();    
private JPanel rightPanel = new JPanel();
private Color col1 = Color.WHITE;
private Color col2 = Color.BLUE;
private Color tempColor;


public Game()
{
    super("Chasing Bombs OFJ2");
    setSize(200,200);
    setVisible(true);
    makeFrame();
}


public void makeFrame()
{
    Container contentPane = getContentPane();
    contentPane.setLayout(new GridLayout());
    leftPanel.setLayout(new BorderLayout());

    //JLabel label2 = new JLabel("Pocahontas");

    JButton button1 = new JButton("One");
    JButton button2 = new JButton("Two");


    add(leftPanel);

    add(middlePanel, new FlowLayout());

    add(rightPanel);

    setGrid();
    //middlePanel.add(label2);
    rightPanel.add(button1);
    rightPanel.add(button2);
    leftPanel.setBackground(Color.PINK);
    middlePanel.setBackground(Color.RED);

}

public void setGrid()
{
    for(int x = 0; x < NUM; x++) {
           gridPanel[x] = new JPanel();
           leftPanel.add(gridPanel[x]);
           if (x % COLS == 0) {
              tempColor = col1;
              col1 = col2;
              col2 = tempColor;}
           if (x % 2 == 0) {
              gridPanel[x].setBackground(col1);}
           else {
             gridPanel[x].setBackground(col2);}
        }
}

}

这是我到目前为止的代码。我怀疑这与setGrid()方法的位置有关。

谢谢

1 个答案:

答案 0 :(得分:1)

  

然后我想在第一个面板中放入5 X 2面板的网格。

leftPanel.setLayout(new BorderLayout());

您将布局设置为BorderLayout,但是您希望使用5x2网格,因此您应该使用GridLayout