【问题标题】:Changing ImageIcon in a Java grid在 Java 网格中更改 ImageIcon
【发布时间】:2013-03-16 00:19:41
【问题描述】:

我有一个简单的棋盘,我也在尝试添加棋子。我想更改图标图像而不添加更多方块。我该怎么做?

我只想覆盖该正方形中的图像,但是我目前所拥有的似乎添加了更多正方形。

国际象棋方块类采用棋子类型和 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);

    }
}

谢谢。

【问题讨论】:

    标签: java swing jbutton chess imageicon


    【解决方案1】:
        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 的基本代码是错误的。您应该将 Icon 作为参数传递。您不应该阅读 ChessSquare 类中的图标。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-04
      • 2011-12-05
      • 1970-01-01
      • 2012-11-27
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      相关资源
      最近更新 更多