java image draw

package com.javacodegeeks.snippets.desktop;
 
import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
 
public class DrawImage {
 
  static Image image;
 
  public static void main(String[] args) {
 
// The image URL - change to where your image file is located!
 
String imageURL = "image.png";
 
// This call returns immediately and pixels are loaded in the background
 
image = Toolkit.getDefaultToolkit().getImage(imageURL);
 
// Create a frame
 
Frame frame = new Frame();
 
// Add a component with a custom paint method
 
frame.add(new CustomPaintComponent());
 
// Display the frame
 
int frameWidth = 300;
 
int frameHeight = 300;
 
frame.setSize(frameWidth, frameHeight);
 
frame.setVisible(true);
 
 }
 
 /**
  * To draw on the screen, it is first necessary to subclass a Component 
  * and override its paint() method. The paint() method is automatically called 
  * by the windowing system whenever component's area needs to be repainted.
  */
  static class CustomPaintComponent extends Component {
 
public void paint(Graphics g) {
 
  // Retrieve the graphics context; this object is used to paint shapes
 
  Graphics2D g2d = (Graphics2D)g;
 
  /**
   * Draw an Image object
   * The coordinate system of a graphics context is such that the origin is at the 
   * northwest corner and x-axis increases toward the right while the y-axis increases 
   * toward the bottom.
   */
 
  int x = 0;
 
  int y = 0;
 
  g2d.drawImage(image, x, y, this);
 
}
 
  }
 
}

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source