2016-05-14 52 views
1

我想知道什麼使用new創建一個JLabel對象,並將其放置在數組中的相應元素中。 (grid [row] [col])的意思。我正在創建一個Tic-Tac-Toe程序。我正在使用for循環來初始化網格。 這裏就是我的for循環:數組中的對應元素

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

}

+0

你在問什麼,我不清楚 –

+0

這顯然是家庭作業的幫助,而且你沒有付出努力。 –

+0

@ChristopherSchneider我不想把整個代碼放進去,因爲它太長了,但這裏是我真正擁有的東西 – dude546546575

回答

2

我會給你一些提示,否則它不會幫助你,我會做你的功課:

  1. 陣列中Java定義如下:Type[] varName = new Type[NumberOfOccurences];或更多維度Type[][] varName = new Type[NumberOfOccurencesForDimension1][NumberOfOccurencesForDimension2];
  2. 把一個表爲一維的陣列需要通過myArray[rowIndex * colIndex + colIndex] = objectToPutIn;
  3. 把一個表分成兩個維度的陣列來計算其指數是簡單的:在Java中myArray[rowIndex][colIndex] = objectToPutIn;
  4. Array索引從0開始。因此,陣列一個元素在索引0處。
+0

非常感謝你......這幫助很多=) – dude546546575

+0

哦順便說一下,我的原始代碼是正確的,它只是我的一個單元比其他單元大...... – dude546546575

+0

很高興聽到您在完成它的好路徑上。 –