How to make a 2d image in Java

I have a quick question about Java. I apologize if this question is really basic, but I'm a beginner Java programmer: D

I want to make a 2d image in a window, but I cannot figure it out. I looked at the graphical API here:

http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Graphics.html

and the only way I could find could work: drawImage (). However, this did not work for me, but maybe this is due to the ImageObserver Observer parameter? I just put null for this, following some tutorial that I found somewhere, but I still have a compilation error: Here is my drawing method:

public void paint(Graphics g) { Image img1 = Toolkit.getDefaultToolkit().getImage("theImage.png"); g.drawImage(img1, 100, 100, null); } // public void paint(Graphics g) 

and here are the methods that call it:

 public static void main(String[] args) { MyGame game = new MyGame(); game.setVisible(true); game.play(); } // public static void main(String[] args) /** The play method is where the main game loop resides. */ public void play() { boolean playing = true; //Graphics g = new Graphics(); while (playing) { paint(); } } // public void play() 

The fact is, when I call paint in a while loop, I get this error: paint (java.awt.Graphics) in MyGame cannot be applied to ()

What does it mean? How can I fix this so that I can successfully display a 2d image?

Thanks in advance: D

+6
source share
3 answers

Instead of paint(); use repaint();

+8
source

You must override paintComponent(Graphics g) . Also, as suggested by @TotalFrickinRockstarFromMars , you should call repaint() .

+3
source
  • You are overcoming paintComponent (Graphics g)

class Game extends JComponent {// Your game class

 Image img = null; public Game() { img = getImage("/theImage.png"); } 

private image getImage (String imageUrl) {

 try { return ImageIO.read(getClass().getResource(imageUrl)); } catch (IOException exp) {} return null; 

}

paintComponent (Graphics g) {

  g.drawImage(img, 100, 100, null); 

}

}

+1
source

Source: https://habr.com/ru/post/894406/


All Articles