簡體   English   中英

在Java網格中更改ImageIcon

[英]Changing ImageIcon in a Java grid

我有一個簡單的棋盤,我也試圖添加棋子。 我想更改圖標圖像而不添加更多方塊。 我怎樣才能做到這一點?

我只想覆蓋那個方塊中的圖像,但是我現在所擁有的圖像似乎增加了更多的方塊。

國際象棋方形類采用棋子類型和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);

    }
}

謝謝。

    x=5;y=8;

你不能這樣做,因為你會得到一個例外。 您的數組是8x8,但它是0偏移量,因此您使用值0-7索引數組。

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

所有聲明都是為您的陣列添加ChessSquare。 它不會將ChessSquare添加到面板中。

正如您所說,無論如何您不想創建新的ChessSquare,您只想更改現有方塊的Icon。 所以代碼應該是這樣的:

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

您創建ChessSquare的基本代碼是錯誤的。 您應該將Icon作為參數傳遞。 你不應該閱讀ChessSquare類中的圖標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM