Reputation: 19
I am trying to get used to using the paintComponent()
method before I incorporate it into my program. However, whenever I try and draw an image to the JPanel
, it is not working. I have put the code below. Any help would be appreciated. Thanks.
public class ExperimentGame extends JPanel{
Image image;
public ExperimentGame(){
JFrame frame = new JFrame();
SwingUtilities.isEventDispatchThread();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setSize(500,500); //my edit
this.setBackground(Color.WHITE);
frame.setVisible(true);
try {
image = ImageIO.read(this.getClass().getResource("spaceship (0).png"));
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image, 50, 50, null);
}
}
public class ExperimentMain {
public static void main(String[] args) {
ExperimentGame game = new ExperimentGame();
}
}
Upvotes: 0
Views: 261
Reputation: 123
A small hack to solve your problem is to call at the bottom of your constructor.
this.revalidate();
this.repaint();
However I recommend you to take a look how Model-View-Controller can be used to update your view whenever something is changed in your model. An example can be found here.
Upvotes: 0