如何在JButtons的ArrayList上显示图像?

时间:2016-11-22 21:20:34

标签: java arraylist

我正在尝试制作伪糖果粉碎风格的游戏。我目前正在尝试将ArrayList中包含的图像添加到ArrayList中的JButton。我不确定如何解决这个问题,而且我现在拥有的东西显然不起作用,因为它不会在JButton中显示图像。这是我的UI代码:

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 个答案:

没有答案