有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java小程序中更改数组中的特定图片?

我正在做一个蛇和梯子的游戏,我有一个小问题。我无法移动这些碎片

基本上,我有一个64块的网格,在一个数组中有64张图片。我也有两张和瓷砖大小相同的图片,我用它们作为移动的部件

当我点击jb按钮时,图片应该会更新

以下是我的代码和我尝试过的内容:

public class SnakesandLadders extends Applet implements ActionListener
{

//Part of the grid
int row = 8;
JLabel a[] = new JLabel [(row*row) + 1];
Panel g = new Panel (new GridLayout (row, row));
JLabel grid;
JButton roll;
int playerNum = 1;
int p1space = 0;
int p2space = 0;

public void init ()
{       
    //The Roll Button
    roll = new JButton ("ROLL");
    roll.addActionListener (this);
    roll.setActionCommand ("roll");

    //The Grid Displayed using a for loop
    for (int rownum = 7 ; rownum >= 0 ; rownum--)
    {
    int number = rownum*8;
        if (rownum % 2 != 0)
        {
            for (int i = 7 ; i >= 0 ; i--)
            {
                a [i+number] = new JLabel (createImageIcon ((i+number) + ".jpg"));
                g.add (a [i+number]);
            }
        }
        else
        {
            for (int i = 0; i < 8; i++)
            {   
                a [i+number] = new JLabel (createImageIcon ((i+number) + ".jpg"));
                g.add (a [i+number]);
            }
        }
    }
        add (g);
        add (roll);
    }

    public void actionPerformed (ActionEvent e)
    {

        if (e.getActionCommand ().equals ("roll"))
        {//NEED TO FIX THIS PART
            {
                int n = (int) ((Math.random () * 6) + 1);
                playerNum++;
                //To choose which picture to update
                if (playerNum % 2 != 0) {
                    turn.setText ("It is Player 1's Turn");
                    p1space = p1space + n;
                    a[p1space] = new JLabel (createImageIcon ("p1.jpg"));
                    }

                else {
                    turn.setText ("It is Player 2's Turn");
                    p2space = p2space + n;
                    a[p2space] = new JLabel (createImageIcon("p2.jpg")); 
                    }
           }
    }

    //The picture update method                
    protected static ImageIcon createImageIcon (String path)
    {
        java.net.URL imgURL = SnakesandLadders.class.getResource (path);
        if (imgURL != null)
        {
            return new ImageIcon (imgURL);
        }
        else
        {
            System.err.println ("Couldn't find file: " + path);
            return null;
        }
    }
}

代码运行,但没有图片更新。我确信我在逻辑上犯了一个错误,我不知道如何将数组中的图片更改为player1和player2。谢谢你的帮助

编辑:我还想了解如何在再次单击滚动按钮时删除上一个图标。谢谢


共 (2) 个答案

  1. # 1 楼答案

    在执行更改后,需要调用revalidate()和repaint()方法,这将在小程序中重新加载更改。 在方法末尾添加这两个方法,如下所示

     public void actionPerformed (ActionEvent e)
     {
       .....
       g.revalidate();
       g.repaint();
     }
    
  2. # 2 楼答案

    您没有将创建的新标签添加到g,因此g无法调用paint方法来呈现标签

    您可以使用^{}来更改图像,而不是创建新的JLabel

    // a[p1space] = new JLabel (createImageIcon ("p1.jpg"));
    a[p1space].setIcon(createImageIcon ("p1.jpg"));