can't get ImageIcon to find my to find my image from C 盘

can't get ImageIcon to find my to find my image from C drive

简单的井字游戏分为两个 类。我知道使用 URL 但我想让它正常工作。这是到目前为止的程序。我大部分是从 youtube 教程中获得的,但现在出现错误消息

线程异常 "main" java.lang.NullPointerException

在 java.desktop/javax.swing.ImageIcon.(未知来源)

在 XOButton.(XOButton.java:17)

在井字游戏中。(TicTacToe.java:24)

在 TicTacToe.main(TicTacToe.java:13)

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.GridLayout;



public class TicTacToe extends JFrame{

JPanel p = new JPanel();
XOButton buttons[] = new XOButton [9];

public static void main(String[] args) {
    new TicTacToe();
}

public TicTacToe() {
    super ("TicTacToe");
    setSize(400,400);
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    p.setLayout(new GridLayout(3,3));
    for (int i=0; i<9; i++) {
        buttons[i] = new XOButton();
        p.add(buttons[i]);
    }

    add(p);

    setVisible(true);
}

}

下一个:

import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class XOButton extends JButton implements ActionListener{

ImageIcon X,O;
byte value = 0;
/*
 0:nothing
 1:X
 2:O
 */

public XOButton() {
    X = new ImageIcon(this.getClass().getResource("C:\Users\mattt\Pictures\X.PNG"));
    O = new ImageIcon(this.getClass().getResource("C:\Users\mattt\Pictures\0.PNG"));
    this.addActionListener(this);
}


public void actionPerformed(ActionEvent e) {
    value++;
    value %= 3;

    switch(value) {
    case 0:
        setIcon(null);
        break;
    case 1:
        setIcon(X);
    case 2:
        setIcon(O);
    }
}

}

您的代码中存在一些问题。

1) 为了防止 nullpointerException,您必须将图像添加到同一个包中。并进行如下更改。

public XOButton() {
    X = new ImageIcon(this.getClass().getResource("X.PNG"));
    O = new ImageIcon(this.getClass().getResource("0.PNG"));
    this.addActionListener(this);
}

2) 在你的 switch case 语句中,case 1 和 2 没有 break 语句。

public void actionPerformed(ActionEvent e) {
    value++;
    value %= 3;

    switch(value) {
    case 0:
        setIcon(null);
        break;
    case 1:
        setIcon(X);
        break;
    case 2:
        setIcon(O);
        break;
    default:
        break;
    }
}