I am a java beginner and for my first project I started building a Monopoly game.
I’m building the GUI in SWING using the Graphics method.
Two problems appeared which I can’t find an answer to.
The first one is that it seems that I can’t set the Background color to my JPanel which I had previously done the same way in another JPanel in the same project.
The second one is that I get a NullPointerException while trying to add an image.I managed to correct this error with a try/catch but it seems that the Graphics won’t paint.Again I’ve used the same method to load and add images in a previous JPanel and it worked.
I should mention that my JFrame at the moment contains 3 elements everyone in there separate classes and are added via BorderLayout().
This is the code for the class that is creating problems:
public class MonopolyBoard extends JPanel{
Image atlantic;
MonopolyBoard() {
this.setBorder(new EtchedBorder());
this.setBackground(new Color( (80), (180), (210) )); //this code dosent work
//this throws exception without try catch
try{
ImageIcon a = new ImageIcon(this.getClass().getResource("../Card/Atlantic Ave.jpg"));
atlantic = a.getImage();
}
catch(NullPointerException e){}
}
public void paint(Graphics g){
}
Graphics2D g2 = (Graphics2D) g;
//this code should draw the image but it dosent
g2.drawImage(atlantic, 100, 100, null);
g.drawImage(atlantic, 100, 100, this);
};
}
You won’t know unless you print the stacktrace inside the catch block. If the constructor,
new ImageIcon(), isn’t throwing the exception and instead is returning a null object, the next line,a.getImage(), will definitely cause a NPE because you can’t call a method on a null object.Instead of this
Try this
The line
Basically, you need to start by seeing what might cause the constructor if ImageIcon to return a null object. That will get you on the right track. It might be something due to a failed getResource() call. A simple way of finding out would be to separate the above line into it’s parts and give them their own result variables. It’s messy and ineficient but that’s how troubleshooting goes sometimes.
You get the picture