首页 文章

将图像放在Java中随机创建的按钮上

提问于
浏览
1

我正在尝试用Java创建一个游戏 . 在游戏中,玩家将通过点击按钮遇到一些障碍 . 到目前为止,这些障碍被定义为整数,如果单击一个按钮,则会出现代表这些对象的数字 . 我想将这些数字更改为图像,但我无法将计数[random1] [random2]从int更改为string . 你有什么建议吗? (我只会在这里添加树障碍及其相关代码) .

public class Tiles implements ActionListener {
    final static int TREES = 10;
    static JFrame frame = new JFrame("The Game");
    JButton[] [] buttons = new JButton[5][5];
    static int [] [] counts = new int [5] [5];
    Panel grid = new Panel();

    public Tiles() {

        frame.setSize(400,400);
        frame.setLayout(new BorderLayout());


        makeGrid();

        frame.add(grid,  BorderLayout.CENTER);
        grid.setLayout(new GridLayout(5,5));
        for (int row = 0; row < buttons.length; row++) {
            for (int col = 0; col < buttons[0].length; col++) {
                buttons [row][col] = new JButton();
                buttons [row][col].addActionListener(this);
                grid.add(buttons[row] [col]);
                buttons[row][col].setBackground(Color.WHITE);
            }

        }



        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }

    public void makeGrid() {


        int numTrees = 2;

        Random random = new Random();


        int i = 0;
        while (i < numTrees)  {
            int random1 = random.nextInt(5);
            int random2 = random.nextInt(5);
            if( counts [random1] [random2] == 0) {
                counts[random1] [random2] = TREES;
                i++;
            }
        }
    }
}

1 回答

  • 1

    您可以将 count 变量的类型从 int[][] 更改为 Map<Integer, Map<Integer, String>> (或使用Guava的 Table 类:https://www.baeldung.com/guava-table) . 然后,您可以使用 count.get(i).get(j) 检索表示 (i,j) 位置图像的 String .

相关问题