ol1ie310
ol1ie310

Reputation: 13

Putting panels inside panels java GUI

I am trying to make a GUI with three panels next to eachother. I then want to put a grid of 5 X 2 panels inside the first pannel. I have managed to create the ttop two but cannot seem to put the extra panels inside. Any help would be much appreciated!

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

}

Here is the code I have so far. I suspect it is something to do with the positioning of the setGrid() method.

THANKS

Upvotes: 0

Views: 878

Answers (1)

camickr
camickr

Reputation: 324098

I then want to put a grid of 5 X 2 panels inside the first pannel.

leftPanel.setLayout(new BorderLayout());

You set the layout to a BorderLayout, but you want a 5x2 grid so you should be using a GridLayout.

Upvotes: 1

Related Questions