用于ImageIcons和优化的java.lang.nullpointerexception

时间:2016-11-09 01:59:10

标签: java java.lang

所以我正在为我的学校开发一个基本的Slot Machine程序,并且我一直得到这个例外。我明白这是什么意思,但我不明白为什么它将我的图像文件读为null。

Exception in thread "main" java.lang.NullPointerException
at ui.UI.<init>(UI.java:22)
at ui.Driver.<init>(Driver.java:27)
at ui.Driver.main(Driver.java:39)

需要任何帮助!

我也不确定我的代码是多么优化所以任何提示都会很棒。

package ui;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.*;


public class UI extends JPanel {
private ArrayList<ImageIcon> images;
private ArrayList<JLabel> labels;
JPanel panel1;
JButton a;

public UI() {
    ImageIcon imageGreen = new ImageIcon("C:/Users/Liam/workspace/CSE115-Lab8a/Images/Green.png");
    ImageIcon imagePurple = new ImageIcon("C:/Users/Liam/workspace/CSE115-Lab8a/Images/Purple.png");
    ImageIcon imageRed = new ImageIcon("C:/Users/Liam/workspace/CSE115-Lab8a/Images/Red.png");

    images.add(imageGreen);
    images.add(imagePurple);
    images.add(imageRed);
    setLayout(new GridLayout(3, 2));


    for(ImageIcon s : images) {
        JLabel label = new JLabel(s);
        labels.add(label);
        add(label);

    }
    a = new JButton("SPIN");
    add(a);

    ActionListener click = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e){
            JLabel label = new JLabel();
            removeAll();
            updateUI();
            Collections.shuffle(labels);
            add(label);
            updateUI();
            }
        };
        a.addActionListener(click);
}
}

驱动程序

package ui;
import javax.swing.*;
import java.awt.*;
import java.awt.Dimension;




public class Driver extends JFrame {

private static final long serialVersionUID = -3413552064004843029L;
private JPanel panelMain;
private UI panel;

public Driver() {
    setLayout(new GridLayout(2, 1));
    setPreferredSize(new Dimension(420, 90));
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panelMain = new JPanel();
    panelMain.setBackground(Color.WHITE);
    panelMain.setBounds(0, 0, 420, 90);
    panelMain.setPreferredSize(new Dimension(200, 40));
    add(panelMain);

    panel = new UI();
    panelMain.add(panel);
    pack();






}

public static void main(String[] args) {
    Driver frame = new Driver();
    frame.setVisible(true);


}

}

谢谢!

1 个答案:

答案 0 :(得分:0)

在此代码中

images.add(imageGreen);

图片为空。它尚未初始化。