2013-03-16 54 views
1

我有一个简单的棋盘,我正在尝试添加棋子。我想更改图标图像而不添加更多方块。我怎样才能做到这一点?在Java网格中更改ImageIcon

我只是想覆盖在那个广场的图像,但是我现在似乎增加了更多的方块。

国际象棋方块类采取件类型和x/y坐标。下面

代码:

国际象棋棋盘:

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class ChessBoard2 
{ 
    public static void main(String[] Args) 
    { 
     JFrame a = new JFrame("Chess"); 
     JPanel panel = new JPanel(); 
     ChessSquare[][] squares = new ChessSquare[8][8]; 
     panel.setLayout(new GridLayout(8,8)); 

     int x = 0; 
     int y = 0; 

     for (x=0; x<8; x++) 
      for(y=0; y<8; y++) 
      { 
       squares[x][y] = new ChessSquare("emptysquare", x, y); 
       panel.add(squares[x][y]); 
      } 

     x=5;y=8; 
     squares[x][y] = new ChessSquare("king", x, y); 

     a.setSize(375,375); 
     a.setContentPane(panel); 
     a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     a.setVisible(true); 

    } 
} 

象棋广场:

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class ChessSquare extends JButton 
{ 
    private int xPosition; 
    private int yPosition; 
    private String filename; 

    public ChessSquare(String type, int x, int y) 
    { 
     super(); 

     xPosition = x; 
     yPosition = y; 

     if (type == "emptysquare") 
     { filename = "EmptySquare.jpg";} 

     if (type == "king") 
     { filename = "king.jpg";} 

     ImageIcon square = new ImageIcon(filename); 
     setIcon(square); 

    } 
} 

感谢。

回答

3
x=5;y=8; 

你不能这样做,因为你会得到一个异常。你的数组是8x8,但它是0偏移量,所以你使用值0-7索引数组。

squares[x][y] = new ChessSquare("king", x, y); 

该声明所要做的就是将ChessSquare添加到您的数组中。它不会将ChessSquare添加到面板。

正如你所说,你不想创建一个新的ChessSquare,你只是想改变一个现有的广场的图标。所以代码应该是这样的:

ChessSquare piece = squares[4][7]; 
piece.setIcon(yourKingIcon); 

您创建ChessSquare的基本代码是错误的。您应该将图标作为参数传递。您不应该阅读ChessSquare课程中的图标。