I’ve found myself incapable of utilizing draw methods to display images within a JFrame. The code following functions exactly the same if the draw(Graphics p) method is never called. What is causing this lack of functionality, and what can be done to fix it? (Assuming that “C:\test\background.png” is a valid path.) There is no compile-time error, and no displayed run-time error. This is the only class in the program. Attempting to draw within a JPanel does nothing to repair the issue.
package gui;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Main extends JFrame{
private Image mainMenuBackground;
private String state;
Graphics g;
Main(){
setSize(800, 600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
state = "main menu";
}
public static void main(String args[]){
Main m = new Main();
m.run();
}
public void loadImages(){
mainMenuBackground = new ImageIcon("C:\\test\\background.png").getImage();
}
public void run(){
try{
loadImages();
draw(g);
pack();
}catch(Exception ex){}
}
public void draw(Graphics p){
Graphics2D g = (Graphics2D) p;
g.drawImage(mainMenuBackground, 0, 0, null);
g.drawRect(0, 0, 50, 50);
}
}
Firstly, this:
will stop you seeing anything that’s going wrong. You say there’s “no displayed run-time error” – well I’m not surprised, as you’ve suppressed everything.
Next, you’re never assigning a value for the instance variable
g, so it will still have a value ofnullwhen you pass it to thedrawmethod, where you then use a local variablegof a different type… and dereference it. That will cause aNullPointerException, which you then catch and ignore.So basically there’s lots going wrong, but fundamentally you don’t get to just declare a
Graphicsvariable and hope that it’ll have a useful value. For “normal” painting operations, the graphics context is provided to your method automatically – or you can create it when working with an image object.