0

I'm relatively new to Java programming and here is some code where it should draw a background Image:

public class Board extends JPanel{
private static final long serialVersionUID = 4759318639631503071L;
public String room = "menu";
public Image backgroundImage;

public Image getBackgroundImage() throws IOException{
    if (room == "menu") {
         backgroundImage = ImageIO.read(new File("assets/background_title.png"));
     }
    return backgroundImage;
}

 @Override
 public void paintComponent(Graphics g) {
     super.paintComponent(g);
     g.drawImage(backgroundImage, 0, 0, this);
 } 
}

I used System.out.println and realized that backgroundImage was null, what have I done wrong here?

2 Answers2

0

You have used == to compare strings

Use if (room.equals("menu"))

instead of

 if (room == "menu") 
Mithilesh Gupta
  • 2,800
  • 1
  • 17
  • 17
0

In Java you should compare String objects using equals() method, since == operator checks whether two references point to exactly the same object.

So:

if(room.equals("menu")) { ... }
Porcupine
  • 324
  • 3
  • 8
  • it still returns null, maybe there's something wrong with the paint method? –  Feb 05 '17 at 00:10
  • And where do you call this `getBackgroundImage()`? Do you call it at all and are you sure that it is called before `JPanel` calls this `paintComponent()`? – Porcupine Feb 05 '17 at 00:13