dude546546575 dude546546575 - 6 months ago 34
Java Question

Corresponding element in arrays

I was wondering what Create a JLabel object using new, and place it in the corresponding element in the array. (grid[row][col]) means. I am creating a Tic-Tac-Toe program.I am using a for loop to initialize the grid.
here's what I have for the for loop:

package tic.tac.toe;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TicTacToe extends JFrame implements ActionListener, MouseListener
{
Container content = this.getContentPane();
//Program Arrays
JLabel [][] grid = new JLabel[' '][' '];
char [][ ]game = new char [' '][' '];
// Graphical User-interface Fields
JButton restart = new JButton("Restart");
JPanel p = new JPanel();
JLabel status = new JLabel("Welcome to Tic-Tac-Toe");
//Primitive Fields
int numClicks = 0 ;
boolean isDone = false;
boolean isXTurn = true;

public TicTacToe()
{//GUI
this.setVisible(true);
this.setTitle("Tic-Tac-Toe");
this.setSize(900,500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//SetLayout

//Add Status Label
content.add(status);
status.setOpaque(true);
status.setBackground(Color.yellow);
status.setForeground(Color.blue);
status.setFont(new Font("Helvetica", Font.BOLD, 12));
//Initailize the Main Panel
p.setLayout(new GridLayout(3,3));
p.setBackground(Color.black);
content.add(p, BorderLayout.CENTER);
//Initialize the grid
for(int row = 0; row<=3;)
{
for (int col = 0; col<=3;)
{
JLabel lbl = new JLabel();
grid[row][col] = lbl;
grid[row][col].addMouseListener(this);
grid[row][col].setOpaque(true);
grid[row][col].setBackground(Color.white);
grid[row][col].setFont(new Font("Helvetica", Font.BOLD, 39));
p.add(grid[row][col]);



}
}

}





@Override
public void actionPerformed(ActionEvent ae)
{

}

@Override
public void mouseClicked(MouseEvent me)
{

}

@Override
public void mousePressed(MouseEvent me)
{

}

@Override
public void mouseReleased(MouseEvent me)
{

}

@Override
public void mouseEntered(MouseEvent me)
{

}

@Override
public void mouseExited(MouseEvent me)
{

}


public static void main(String[] args) {
TicTacToe tTT = new TicTacToe();
}


}

Answer

I will give you some hints, otherwise it won't help you I would do your homework :

  1. Arrays in Java are defined this way : Type[] varName = new Type[NumberOfOccurences]; OR more dimensions Type[][] varName = new Type[NumberOfOccurencesForDimension1][NumberOfOccurencesForDimension2];.
  2. Putting a table into an array of one dimension needs to calculate its index by myArray[rowIndex * colIndex + colIndex] = objectToPutIn;
  3. Putting a table into an array of two dimensions is trivial : myArray[rowIndex][colIndex] = objectToPutIn;
  4. Array index in Java starts at 0. So an array of one element is at index 0.
Comments