making a chessboard with arrays of JPanel - java

I 'm doing a chessboard , my idea is to make an array of JPanels , each box is a JPanel with color, the problem I have , when I make such assignment
" chessboard [ rows ] [columns ] = b" and compile gives me an exception .
Why the assignment gives me an error ?
How I can fix it?
Is the layout grid , should go in the JFrame or JPanel ?
thanks.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
First Class
public class ChessBoard extends JPanel {
private JPanel[][] chessBoardSquares = new JPanel[8][8];
private final JPanel tile;
public ChessBoard () {
tile = new JPanel();
tile.setLayout(new GridLayout(8, 8));
for (int rows = 0; rows < 8; rows++) {
for (int columns = 0;columns< 8;columns++) {
JPanel b = new JPanel();
chessBoardSquares = new JPanel[rows][columns];
if ((rows+columns +1)%2 == 0){
b.setBackground(Color.WHITE);
chessBoardSquares[rows][columns] = b;
}
tile.add( chessBoardSquares [rows][columns]);
}
}
}
}
main
public class example {
public static void main(String[] args) {
JFrame window = new JFrame();
ChessBoard chessBoard = new ChessBoard();
window.add( chessBoard );
window.setVisible(true);
}
}

You're not filling your array properly.
This
for (int rows = 0; rows < 8; rows++) {
for (int columns = 0;columns< 8;columns++) {
JPanel b = new JPanel();
// ***** this creates a completely new array *******
chessBoardSquares = new JPanel[rows][columns];
should be
for (int rows = 0; rows < 8; rows++) {
for (int columns = 0;columns< 8;columns++) {
JPanel b = new JPanel();
// this assigns a JPanel to an array item
chessBoardSquares[rows][columns] = new JPanel();
Also as an aside, I don't see where you're adding the tile JPanel to your GUI, and you'll want to fix this.

It should be better like this :
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ChessBoard extends JPanel {
private final JPanel[][] tiles = new JPanel[8][8];
public ChessBoard() {
Dimension dims = new Dimension(64, 64);
setLayout(new GridLayout(8, 8));
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
JPanel b = new JPanel();
b.setPreferredSize(dims);
b.setMinimumSize(dims);
if ((i + j + 1) % 2 == 0) {
b.setBackground(Color.WHITE);
} else {
b.setBackground(Color.BLACK);
}
add(b);
tiles[i][j] = b;
}
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Chess");
ChessBoard chessBoard = new ChessBoard();
f.add(chessBoard);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

Related

Is there a way to place JButtons with different spaces in the begining at the GridBagLayout?

I'm trying to do something like this:
But I can't leave spaces before the buttons. I have tried to add invisible buttons, but nothing has changed.
for (int i = 0; i < gameSize; i++ ){
c.gridwidth = (i+1)*2;
c.gridx = 0;
c.gridy = 4*i;
JRadioButton temp = new JRadioButton();
temp.setVisible(false);
board.add(temp,c);
for(int j = 0; j < gameSize; j++){
c.gridwidth = 4;
c.gridx = 2+(4*j);
c.gridy = 2+(4*i);
cells[i][j] = new JButton();
cells[i][j].setBackground(Color.white);
board.add(cells[i][j],c);
}
}
It's look like [this:
when I made them visible. I didn't get why width of them is still 4 even though I'm assigning it to (i+1)*2.
I'm new to Java and very very new to Java GUI. So, maybe I didn't figure out the most basic thing. Thanks for advices!
I created the following GUI.
In order to do this, I had to use a combination of Swing layouts.
The buttons on each row are created in a JPanel with a GridLayout. The row is created with a row JPanel with a FlowLayout, using a dummy JLabel and the button row JPanel.
The main JPanel uses a GridLayout of (0, 1) to create the staggered effect. The dummy JLabel in each row gets bigger by half the size of the JButtons.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GridBagLayoutStaggeredGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new GridBagLayoutStaggeredGUI());
}
#Override
public void run() {
JFrame frame = new JFrame("Staggered Layout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
int gameSize = 8;
int buttonSize = 50;
int inset = 2;
JButton[][] cells = new JButton[gameSize][gameSize];
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
for (int i = 0; i < gameSize; i++) {
JPanel innerPanel = new JPanel(
new FlowLayout(FlowLayout.LEADING, 0, 0));
JLabel label = new JLabel();
label.setPreferredSize(new Dimension(inset, buttonSize));
innerPanel.add(label);
innerPanel.add(createRowPanel(cells[i], buttonSize));
panel.add(innerPanel);
inset += buttonSize / 2;
}
return panel;
}
private JPanel createRowPanel(JButton[] cells, int buttonSize) {
JPanel panel = new JPanel(new GridLayout(0, cells.length, 0, 0));
for (int i = 0; i < cells.length; i++) {
cells[i] = new JButton();
cells[i].setBackground(Color.white);
cells[i].setPreferredSize(new Dimension(buttonSize, buttonSize));
panel.add(cells[i]);
}
return panel;
}
}
The GridBagLayout can only calculate the width of a column if there is a component added to the column with a "gridwidth" of 1.
In your example you have 6 button each with a "gridwidth" of 2, implying you really want 12 columns. But what should the width of each column be?
The example below shows how to allocate a minimum width for each column. Now each of the 12 columns will have a minimum width based on the value specified.
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class GridBagLayoutMRE extends JPanel
{
public GridBagLayoutMRE()
{
int gameSize = 6;
int columnsNeeded = (gameSize * 3);
int cellSize = 30;
Dimension buttonSize = new Dimension(cellSize * 2, cellSize);
GridBagLayout gbl = new GridBagLayout();
setLayout( gbl );
int[] columnWidths = new int[columnsNeeded];
Arrays.fill(columnWidths, cellSize);
gbl.columnWidths = columnWidths;
GridBagConstraints gbc = new GridBagConstraints();
for (int i = 0; i < gameSize; i++)
{
gbc.gridx = 0;
gbc.gridy = i;
gbc.gridwidth = 1;
JRadioButton rb = new JRadioButton();
rb.setPreferredSize( new Dimension(60, cellSize) );
add(rb, gbc);
gbc.gridx = i + 1;
gbc.gridwidth = 2;
for (int j = 0; j < gameSize; j++)
{
JButton button = new JButton();
button.setPreferredSize( buttonSize );
add(button, gbc);
gbc.gridx = gbc.gridx + gbc.gridwidth;
}
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("GridBagLayoutMRE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( new GridBagLayout() );
frame.add(new GridBagLayoutMRE());
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}

How to update button colors continually [JAVA SWING]

I made a class which takes as parameters 2 dimentions ( n,m ) and a matrix ( mat ). This class makes a JFrame,fills it with buttons colored white(for 1's) or black( for 0's).
The issue is, the matrix being sent is continually changing and i want the button colors to update. If i set the mainframe game = new mainframe(n,m,mat) inside the loop im changing the matrix in,it continually spawns JFrame windows.
I read some stuff on this site that using repaint() or revalidate() could do something like this. I tried putting it in various segments of code but had no luck with it.
The main class is just a loop which calls "mainframe" and updates a matrix in a loop. Here is the class which makes the actual GUI work:
package game;
import java.awt.Color;
public class mainframe extends Jframe {
public mainframe(int n,int m,int mat[][]){
JButton[] buttons = new JButton[n*m];
setSize(600,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(new GridLayout(n,m));
for(int i = 0; i<n*m;i++) {
buttons[i] = new JButton();
}
int counter = 0;
for(int j=0;j<n;j++){
for(int k=0;k<m;k++){
if(mat[j][k]==0){
buttons[counter].setBackground(Color.BLACK);
}
add(buttons[counter]);
counter++;
}
}
}
}
Put the setVisible(true); or revalidate(); after you added your components. Better work with the frame content pane.
import javax.swing.*;
import java.awt.*;
class Scratch {
public static void main(String[] args) throws InterruptedException {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(600, 400);
jFrame.setVisible(true);
for (int i = 5; i < 10; ++i) {
jFrame.setContentPane(createPanel(i, i, new int[i][i]));
jFrame.revalidate();
Thread.sleep(1000);
}
}
public static JPanel createPanel(int n, int m, int[][] mat) {
JButton[] buttons = new JButton[n * m];
JPanel jPanel = new JPanel();
jPanel.setLayout(new GridLayout(n, m));
for (int i = 0; i < n * m; i++) {
buttons[i] = new JButton();
}
for (int j = 0; j < n; j++) {
for (int k = 0; k < m; k++) {
int index = k + k * j;
if (mat[j][k] == 0) {
buttons[index].setBackground(Color.BLACK);
}
jPanel.add(buttons[index]);
}
}
return jPanel;
}
}

Random placement of JPanels in Jframe

I'm a beginning Java student and I'm trying to either randomly change the position of JPanels within a JFrame or randomly change the label in the JPanel. I managed to get a grid to randomly change colors and thought I would try to make something like the changing 1s and 0s at the beginning of the Matrix movie. So far I'm unable to achieve the desired results and would like some help. In my code I have the random color changer (I know it's not what I need, but I'm assuming I need to add correct code to the Action Listener).
Here's what I have:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class MatrixGrid extends JFrame {
final int grid = 20;
final int pnlCnt = grid * grid;
final JFrame frame = new JFrame("WELCOME TO THE MATRIX");
final JPanel[] panels = new JPanel[pnlCnt];
Timer t;
public MatrixGrid() {
for (int i = 0; i < panels.length; i++) {
final String[] labels = new String[]{"0", "1"};
Random rand = new Random();
int index = rand.nextInt(labels.length);
String randomTitle = labels[index];
JLabel label = new JLabel(randomTitle, JLabel.CENTER);
label.setForeground(Color.green);
label.setVerticalAlignment(JLabel.CENTER);
panels[i] = new JPanel();
panels[i].setBackground(Color.BLACK);
panels[i].add(label);
frame.getContentPane().add(panels[i]);
}
frame.setLayout(new GridLayout(grid,grid));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
frame.setVisible(true);
//I know this won't do what I want, but I think this is where I need
//to add code to randomize the panels or labels
ActionListener action = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < panels.length; i++) {
Color mix = new Color(255,255,255);
Random random = new Random();
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
if(mix != null)
{
r = (r + mix.getRed()) / 2;
g = (g + mix.getGreen()) / 2;
b = (b + mix.getBlue()) / 2;
}
Color color = new Color(r, g, b);
panels[i].setBackground(color);
}
}
};
t = new Timer(100, action);
t.setRepeats(true);
t.start();
}
public static void main(String args[]) {
MatrixGrid q = new MatrixGrid();
}
}
Could someone point me in the right direction? I've googled until my eyes are about to fall out of my head. Any help would be very much appreciated. Cheers
I dont know if i did what You want.
I changed the for in the constructor:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class NewClass extends JFrame {
final int grid = 20;
final int pnlCnt = grid * grid;
final JFrame frame = new JFrame("WELCOME TO THE MATRIX");
final JPanel[] panels = new JPanel[pnlCnt];
Timer t;
public NewClass() {
for (int i = 0; i < panels.length; i++) {
final String[] labels = new String[]{"0", "1"};
final Random rand = new Random();
int index = rand.nextInt(labels.length);
String randomTitle = labels[index];
final JLabel label = new JLabel(randomTitle, JLabel.CENTER);
Timer lblt = new Timer(00, new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
label.setText(labels[rand.nextInt(labels.length)]);
}
});
lblt.setRepeats(true);
lblt.start();
label.setForeground(Color.green);
label.setVerticalAlignment(JLabel.CENTER);
panels[i] = new JPanel();
panels[i].setBackground(Color.BLACK);
panels[i].add(label);
frame.getContentPane().add(panels[i]);
}
frame.setLayout(new GridLayout(grid, grid));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
frame.setVisible(true);
//I know this won't do what I want, but I think this is where I need
//to add code to randomize the panels or labels
ActionListener action = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < panels.length; i++) {
Color mix = new Color(255, 255, 255);
Random random = new Random();
int r = random.nextInt(255);
int g = random.nextInt(255);
int b = random.nextInt(255);
if (mix != null) {
r = (r + mix.getRed()) / 2;
g = (g + mix.getGreen()) / 2;
b = (b + mix.getBlue()) / 2;
}
Color color = new Color(r, g, b);
panels[i].setBackground(color);
}
}
};
t = new Timer(00, action);
t.setRepeats(true);
t.start();
}
public static void main(String args[]) {
NewClass q = new NewClass();
}
}
Edit: I put the whole code, try to run it and see if it does what You want.

Gap between JPanels in GridLayout

The code below produces nine individual JPanels in which are 9 buttons. The nine JPanels are arranged onto a base JPanel using GridLayout. This base JPanel is then placed onto the ContentPane using Border Layout. I'm using borders for the JButtons and each individual JPanel to clearly define their separation. The JButtons inside each JPanel look fine but there is a gap between the JPanels which is causing the appearance of a double line which is bugging the hell out of me. I've tried adding each individual JPanel onto the ContentPane directly but this does nothing. Totally stumped and wondering if anyone has any suggestions?
P.S. I know the mass of duplicate code needs re-factoring in a bad way and it will, this is just for mock-up purposes.
Thanks,
import java.awt.*;
import javax.swing.*;
import javax.swing.UIManager.*;
public class View1 extends JFrame
{
private JPanel basePanel;
private JPanel childPanel1;
private JPanel childPanel2;
private JPanel childPanel3;
private JPanel childPanel4;
private JPanel childPanel5;
private JPanel childPanel6;
private JPanel childPanel7;
private JPanel childPanel8;
private JPanel childPanel9;
private int row = 3;
private int column = 3;
private JButton[][] squares1;
private JButton[][] squares2;
private JButton[][] squares3;
private JButton[][] squares4;
private JButton[][] squares5;
private JButton[][] squares6;
private JButton[][] squares7;
private JButton[][] squares8;
private JButton[][] squares9;
private Font numberFont;
public View1()
{
setSize(400,400);
setTitle("2013");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
basePanel = new JPanel();
basePanel.setLayout(new GridLayout(row, column, 0, 0));
numberFont = new Font("sansserif", Font.BOLD, 32);
childPanel1Setup();
childPanel2Setup();
childPanel3Setup();
childPanel4Setup();
childPanel5Setup();
childPanel6Setup();
childPanel7Setup();
childPanel8Setup();
childPanel9Setup();
basePanel.add(childPanel1);
basePanel.add(childPanel2);
basePanel.add(childPanel3);
basePanel.add(childPanel4);
basePanel.add(childPanel5);
basePanel.add(childPanel6);
basePanel.add(childPanel7);
basePanel.add(childPanel8);
basePanel.add(childPanel9);
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(basePanel, BorderLayout.CENTER);
}
public void childPanel1Setup()
{
childPanel1 = new JPanel();
childPanel1.setLayout(new GridLayout(row, column, 0, 0));
childPanel1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares1 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares1[rows][cols] = new JButton();
squares1[rows][cols].setSize(32, 32);
squares1[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares1[rows][cols].setBackground(Color.WHITE);
childPanel1.add(squares1[rows][cols]);
}
}
}
public void childPanel2Setup()
{
childPanel2 = new JPanel();
childPanel2.setLayout(new GridLayout(row, column, 0, 0));
childPanel2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares2 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares2[rows][cols] = new JButton();
squares2[rows][cols].setSize(32, 32);
squares2[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares2[rows][cols].setBackground(Color.WHITE);
childPanel2.add(squares2[rows][cols]);
}
}
}
public void childPanel3Setup()
{
childPanel3 = new JPanel();
childPanel3.setLayout(new GridLayout(row, column, 0, 0));
childPanel3.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares3 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares3[rows][cols] = new JButton();
squares3[rows][cols].setSize(32, 32);
squares3[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares3[rows][cols].setBackground(Color.WHITE);
childPanel3.add(squares3[rows][cols]);
}
}
}
public void childPanel4Setup()
{
childPanel4 = new JPanel();
childPanel4.setLayout(new GridLayout(row, column, 0, 0));
childPanel4.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares4 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares4[rows][cols] = new JButton();
squares4[rows][cols].setSize(32, 32);
squares4[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares4[rows][cols].setBackground(Color.WHITE);
childPanel4.add(squares4[rows][cols]);
}
}
}
public void childPanel5Setup()
{
childPanel5 = new JPanel();
childPanel5.setLayout(new GridLayout(row, column, 0, 0));
childPanel5.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares5 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares5[rows][cols] = new JButton();
squares5[rows][cols].setSize(32, 32);
squares5[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares5[rows][cols].setBackground(Color.WHITE);
childPanel5.add(squares5[rows][cols]);
}
}
}
public void childPanel6Setup()
{
childPanel6 = new JPanel();
childPanel6.setLayout(new GridLayout(row, column, 0, 0));
childPanel6.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares6 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares6[rows][cols] = new JButton();
squares6[rows][cols].setSize(32, 32);
squares6[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares6[rows][cols].setBackground(Color.WHITE);
childPanel6.add(squares6[rows][cols]);
}
}
}
public void childPanel7Setup()
{
childPanel7 = new JPanel();
childPanel7.setLayout(new GridLayout(row, column, 0, 0));
childPanel7.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares7 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares7[rows][cols] = new JButton();
squares7[rows][cols].setSize(32, 32);
squares7[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares7[rows][cols].setBackground(Color.WHITE);
childPanel7.add(squares7[rows][cols]);
}
}
}
public void childPanel8Setup()
{
childPanel8 = new JPanel();
childPanel8.setLayout(new GridLayout(row, column, 0, 0));
childPanel8.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares8 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares8[rows][cols] = new JButton();
squares8[rows][cols].setSize(32, 32);
squares8[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares8[rows][cols].setBackground(Color.WHITE);
childPanel8.add(squares8[rows][cols]);
}
}
}
public void childPanel9Setup()
{
childPanel9 = new JPanel();
childPanel9.setLayout(new GridLayout(row, column, 0, 0));
childPanel9.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares9 = new JButton[row][column];
for(int rows = 0; rows < this.row; rows++)
{
for(int cols = 0; cols < this.column; cols++)
{
squares9[rows][cols] = new JButton();
squares9[rows][cols].setSize(32, 32);
squares9[rows][cols].setBorder(BorderFactory.createLineBorder(Color.BLACK));
squares9[rows][cols].setBackground(Color.WHITE);
childPanel9.add(squares9[rows][cols]);
}
}
}
}
I believe it's because the Layout Manager for JPanels is FlowLayout which includes a margin. When you create the panels, set their layout to GridLayout which will give you 0 margin.
Also have you done setVgap(0); and setHgap(0); for the GridLayout?
GridLayout makes all component to be of the same size. If it needs to layout matrix of 3x3 components inside JPanel that it 100x100 pixels, each component will be 33x33 pixels and there will be on extra pixel at the right and at the bottom because 100 is not factor of 3. If JPanel is 101x101 pixels, there will be extra pixels at all four edges.
Consider using GridBagLayout or Box or some other layout that is smarter than GridLayout.

How a JPanel displays different colors from an array of colors?

The problem is when I set the background color of the square JPanel as square.setBackground(colors[j]) the square draws only the first color of the list of colors without displaying the other 3. This is my code:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
#SuppressWarnings({ "unused", "serial" })
public class RegionPartition extends JFrame
{
JLayeredPane layeredPane;
JPanel regionBoard;
JLabel regionPiece;
private static int DELAY = 200;
private Color[] colors = new Color[]{Color.PINK, Color.GREEN, Color.BLACK, Color.RED};
public RegionPartition()
{
Dimension boardSize = new Dimension(500, 500);
// Use a Layered Pane for this this application
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize(boardSize);
regionBoard = new JPanel();
layeredPane.add(regionBoard, JLayeredPane.DEFAULT_LAYER);
regionBoard.setLayout( new GridLayout(4, 4) );
regionBoard.setPreferredSize( boardSize );
regionBoard.setBounds(0, 0, boardSize.width, boardSize.height);
Random random = new Random();
for (int i = 0; i < 16; i++) {
JPanel square = new JPanel(new BorderLayout());
square.setBorder(BorderFactory.createLineBorder(Color.black));
regionBoard.add( square );
square.setBackground(Color.green);
int j=0;
square.setBackground(colors[j]);
j++;
}
}
{
JPanel panel = new JPanel()
{
Clients[] c = new Clients[128];
Random random = new Random();
private final int SIZE = 450;
private int DELAY = 9999999;
public void paintComponent (Graphics g)
{
super.paintComponent(g);
for (int i=0; i<c.length; i++)
{
int x = ( int ) ( random.nextFloat() * SIZE ) + 10;
int y = ( int ) ( random.nextFloat() * SIZE ) + 10;
g.drawOval( x, y, 10, 10 );
g.fillOval(x, y, 10, 10);
}
for (int j=0; j<DELAY; j++)
{
repaint();
}
}
};
panel.setOpaque(false);
//Set the glass pane in the JFrame
setGlassPane(panel);
//Display the panel
panel.setVisible(true);
}
public static void main(String[] args)
{
JFrame frame = new RegionPartition();
frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE );
frame.pack();
frame.setResizable(true);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
protected void paintComponent(Graphics g)
{
// TODO Auto-generated method stub
}
}
That is because you are always setting j to 0 on each iteration:
int j=0;
square.setBackground(colors[j]);
j++;
you may want to change j for an i or do a nested loop, that depends on what you really want to do here.
If you want to make all 16 squares have all four colors in a grid like manner, you might want to change your loop to something like:
for (int i = 0; i < 16; i++) {
JPanel square = new JPanel(new GridLayout(2,2));
square.setBorder(BorderFactory.createLineBorder(Color.black));
regionBoard.add( square );
for(int j=0; j<4; ++j){
JPanel insideSquare = new JPanel();
insideSquare.setBackground(colors[j]);
square.add(insideSquare);
}
}
Because you only have 4 colors in your color array, but your loop index exceeds this, you could use:
square.setBackground(colors[ i % colors.length]);
to alternate the colors of your squares.
You are instantiating int j within the scope of your for loop, so its value is not preserved across multiple iterations. You should declare it at a point in your code to allow it scope over your entire for loop.
int j = 0;
<for loop>
square.setBackground(colors[j]);
j++;
<end for>
However, your j is serving the purpose of i in this situation, where i is sufficient as an array index. It would be more correct to remove j entirely and instead do the following:
square.setBackground(colors[i]);

Categories