Search code examples
javaswinguser-interfaceimageicon

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


Simple tic tac toe seperated into two classes. I'm aware of using a URL but i want to get this working. Here is the program so far. i got it from a youtube tutorial for the most part, but now the error message

Exception in thread "main" java.lang.NullPointerException

at java.desktop/javax.swing.ImageIcon.(Unknown Source)

at XOButton.(XOButton.java:17)

at TicTacToe.(TicTacToe.java:24)

at 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);
}

}

next:

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);
    }
}

}

Solution

  • There are some issues in your code.

    1) To prevent nullpointerException you have to add the images into same package. and do the changes as below.

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

    2) In your switch case statement case 1 and 2 doesn't has break statement.

    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;
        }
    }