Link to home
Start Free TrialLog in
Avatar of Vanavah Edwards
Vanavah Edwards

asked on

How to draw an image on screen in Java?

Please help draw my image on screen.  Below is the code I have been struggling with only one module.  I cannot get the image draw to screen.  Can you please help me.

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class DrawImageToScreen {
   
    public static void main(String[] args) {
   
        // TODO code application logic here
        JFrame frame= new JFrame("JavaTutorial.net");      
      //frame.getContentPane().add(new AsycudaWorld());
        Image image = Toolkit.getDefaultToolkit().getImage("TestingInternetConnection.jpg");
        Graphics g = null;
        g.drawString("Hello to JavaTutorial.net", 10, 10);
        //g.drawImage(image, 0, 0, frame);

      frame.setSize(800, 600);
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setResizable(false);
   
    }
}
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You need to take a basic "Java custom painting" tutorial - your approach is wrong.
Avatar of Vanavah Edwards
Vanavah Edwards

ASKER

Can you please recommend one that is very basic that I can build on?
I tried the following one.  IBut it would not print the image in the JFrame.  Can you please help me?

public class DrawImage extends JPanel {

    public void paint(Graphics g){
            
      Image image = Toolkit.getDefaultToolkit().getImage("TestingInternetConnection.jpg");
        g.drawImage(image, 10, 10, this);
    }
   
    public static void main(String[] args) {
   
        // TODO code application logic here
        JFrame frame= new JFrame("JavaTutorial.net");      
      frame.getContentPane().add(new AsycudaWorld());
            frame.setSize(600, 400);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setResizable(false);
               
   }            
}
ASKER CERTIFIED SOLUTION
Avatar of Abdellatif ELFAKER
Abdellatif ELFAKER

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I tried all types of examples and nothing works.  This is the best solution.  This expert is very good.
Thank you so much for that solution.  I don't even mind paying something for your time.

I want to put about 3 gif images in sequence on top of the image so as to display some helpful information to the user.  Using the solution with the same image you provided above, can you please tell me how to draw another image (gif image) on top of this one and how to remove it.
Hello I got it done using your same code with a few modifications.  However, the gif file on top to the image is flat.  It is not animated.  How can I fix this problem?