无法使用JList组件填充arraylist

时间:2019-04-03 15:25:24

标签: java swing

对于上下文,我正在尝试创建一个扫雷副本。我已经有了一个已经生成了地雷的网格。现在我要做的是将我存储在单独的JList中的炸弹的坐标与每个空白图块的坐标进行比较,以检查是否接近(因此,如果附近有一颗炸弹,则打印数字1,依此类推,如果您玩过扫雷,你知道我的意思)。无论如何,我只需要将此JList与2d数组进行比较即可,该数组存储我拥有的JLabel的所有值(或坐标),它们代表每个图块(常规或炸弹)。我曾尝试将JList的炸弹坐标放到arraylist中,因为我发现比较这两种数据类型会更容易,但是当我这样做时,arraylist只返回空白值。

public class initMineField extends JFrame {

DefaultListModel<Integer> listModel = new DefaultListModel<>(); //The JList I want to compare
JList<Integer> intJList = new JList<>(listModel);

public int rows=1000;
public int cols=750;

public int i = 0;
public int j = 0;



 public initMineField(){

    JPanel panel = new JPanel();
   getContentPane().add(panel);



    JFrame window = new JFrame();
    window.setSize(1015,885);
    window.setVisible(true);
    window.setTitle("MineSweeper2");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setLayout(null);
    panel.setBounds(0,100,rows,cols);
    //window.setResizable(false);
    window.add(panel);

    List<Integer> list = new ArrayList<Integer>();

    int  inds []= intJList.getSelectedIndices();

    for(int i = 0 ; i < inds.length;i++) //Main  focus is here
    {
       list.add((Integer) (intJList.getModel().getElementAt(inds[i])));
    }

    JPanel Grid[][] = new JPanel[rows][cols]; //The 2D array I want to compare
    for ( i = 0; i< Grid.length; i += 50) {
        for(j = 0; j < Grid[i].length; j+= 50) {

            int v = (int) (Math.random() * 15); //decides if tiles are bomb/tile not of concern

            ImageIcon icon = new ImageIcon("download2a.fw.png");
            JLabel label = new JLabel(icon);

            ImageIcon icon2 = new ImageIcon("download1.fw.jpg");
            JLabel bomb = new JLabel(icon2);

            Grid[i][j]= new JPanel(new GridLayout(rows,cols));
            panel.setLayout(null);

            Image image = icon.getImage(); //ignore these lines
            Image newimg = image.getScaledInstance(50, 50,   java.awt.Image.SCALE_SMOOTH);
            icon = new ImageIcon(newimg);
            label.setIcon(icon);

            Image image2 = icon2.getImage(); //ignore
            Image newimg2 = image2.getScaledInstance(50, 50,  java.awt.Image.SCALE_SMOOTH);
            icon2 = new ImageIcon(newimg2);
            bomb.setIcon(icon2);

            if( v <= 10) { //The Jlabel for regular tiles
            label.setBounds(i,j,50,50);
            panel.add(label);
            }
            else { //The Jlabel for bombs
            bomb.setBounds(i,j,50,50);
            panel.add(bomb);
            listModel.addElement(i);
            listModel.addElement(j);
            }

            if(Grid[i][j] != list) { //I'm trying to isolate the blank tiles on this line
                System.out.println(list);
            }


        }



    }







    }
} 

列表仅返回空白值,这就是我遇到的问题。

0 个答案:

没有答案