I have been trying this for hours now. I have a class that extends JComponent, and in its paintComponent I am trying to draw an image, but I am not being able to. Here is my code:
public class Main extends JComponent{
public static void main(String[] args) {
Main main = new Main();
JFrame frame = new JFrame(Info.getGameTitle());
frame.add(main);
frame.setSize(Info.getWidth(), Info.getHeight());
frame.setResizable(false);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.out.println("Window closed");
System.exit(0);
}
});
frame.setAlwaysOnTop(true);
frame.setFocusable(true);
frame.setAutoRequestFocus(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Graphics g = main.getGraphics();
main.paint(g);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage image = null;
try {
image = ImageIO.read(new FileInputStream("images/01.jpg"));
}catch(FileNotFoundException e) {
System.out.println("Could not find file!");
e.printStackTrace();
}catch(IOException e) {
System.out.println("Could not read file!");
e.printStackTrace();
}
g.drawImage(image, 0, 0, this);
}
}
It is not throwing any exceptions, so the image appears to be loaded. However, nothing appears on the screen. If I try to draw shapes or text, that works fine. What am I doing wrong?
EDIT: Now I have supplied a working example.