Use an off-screen image in an application. - Java 2D Graphics

Java examples for 2D Graphics:Paint

Description

Use an off-screen image in an application.

Demo Code

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JPanel;

class OffScreenImagePanel extends JPanel {
  public OffScreenImagePanel() {
    this.setPreferredSize(new Dimension(200, 200));
  }//from www  . j a v a2s .  c o m

  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Create an offscreen image and fill a rectangle with red
    int w = this.getWidth();
    int h = this.getHeight();
    Image offScreenImage = this.createImage(w, h);
    Graphics imageGraphics = offScreenImage.getGraphics();
    imageGraphics.setColor(Color.RED);
    imageGraphics.fillRect(0, 0, w, h);

    // Draw the offscreen image on the JPanel
    g.drawImage(offScreenImage, 0, 0, null);
  }
}

Related Tutorials