有 Java 编程相关的问题?

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

java如何在JButton的ArrayList上显示图像?

我正在尝试制作一个伪糖果粉碎风格的游戏。我目前正在尝试将ArrayList中包含的图像添加到ArrayList中的JButtons中。我不确定该怎么做,而且我目前拥有的东西显然不起作用,因为它没有显示JButtons中的图像。以下是我的用户界面代码:

package code.ui;

import java.awt.GridLayout;
import java.awt.Image;    
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;


import code.model.Model;

public class gameUI implements Runnable {

private JFrame _frame;
private Model _model;

private ArrayList<JButton> _buttons;
private JButton _spin;

@Override public void run() {
    _frame = new JFrame("Switcher");
    _frame.getContentPane().setLayout(new GridLayout(5,5));

    _model = new Model();  // create the model for this UI
    _model.addObserver(this);  



    _buttons = new ArrayList<JButton>();
    for (int i=0; i<25; i++) {
        JButton button = new JButton();
        _buttons.add(button);
        _frame.getContentPane().add(button);
        _buttons.get(i).setIcon(new ImageIcon("Images/"+_model.getImageFileName(i)));
        Collections.shuffle(_buttons);
    }


    _frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    _frame.pack();
    _frame.setVisible(true);
}



}

这是我的模型代码:

package code.model;

import java.util.ArrayList;
import java.util.Random;

import javax.swing.ImageIcon;


public class Model {

    private Random _rand;  
    private ArrayList<String> _imageFileNames;  
    private ArrayList<String> _imageCurrentValues;  

    public Model() {
        _rand = new Random();

        _imageFileNames = new ArrayList<String>();
        _imageFileNames.add("Red.png");
        _imageFileNames.add("Green.png");
        _imageFileNames.add("Purple.png");
        _imageFileNames.add("Tile-0.png");
        _imageFileNames.add("Tile-1.png");
        _imageFileNames.add("Tile-2.png");
        _imageFileNames.add("Tile-3.png");
        _imageFileNames.add("Tile-4.png");
        _imageFileNames.add("Tile-5.png");

        _imageCurrentValues = new ArrayList<String>();
        for(int i=0; i<25; i=i+1) {
            _imageCurrentValues.add(i,null);
        }

    }


    public String getImageFileName(int i) {
        return _imageCurrentValues.get(i);
    }

}

共 (0) 个答案