Search code examples
javaimageappletgraphics2d

How do I use graphics2D in paint or is there a better way to do this?


I want to use graphics2D but I can't get I get it to display my graphics. Is there a better way to go about this that would allow me to use repaint()? Eventually I want to make have a image set as a background and be able to draw on it then save the contents of the frame as a image.

import java.awt.image.*;
import javax.imageio.ImageIO;
import javax.swing.*;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.swing.JApplet;
import java.awt.*;

// assume that the drawing area is 150 by 150
public class test extends JApplet
{
  final int radius = 25;
  int width = 200, height = 200;

 BufferedImage img = new BufferedImage(
   width, height, BufferedImage.TYPE_INT_ARGB);

  public void paint (  )
  { 
    Graphics2D g = img.createGraphics();
    g.setColor( Color.orange );
    g.fillRect( 0, 0, 150, 150 );
    g.setColor( Color.black );

    g.drawOval( (150/2 - radius), (150/2 - radius), radius*2, radius*2 );
   }
}

Solution

  • Ok so,

    1. You have public void paint( ) what the hell is this doing lol? You need a graphics object. public void paint(Graphics g) is like the default method which gets called automatically when your applet is initialised.

    2. You have Graphics2D g = img.createGraphics(); when you need to use your default Graphics g object and cast it into a Graphics2D object like so Graphics2D g2d = (Graphics2D) g;

    3. You should search for a little more information on double buffering too :)

    anyway... This code works so take from it what you want :)

    P.S Note how I implemented Runnable; You do not need to do this if you only want to use the Graphics2D code. It is just making the class a thread and is used for game frame rates :)

    Hope this helped.

    import java.applet.*;
    import java.awt.*;
    
    
    public class Test extends Applet implements Runnable{
    
    public boolean isRunning = false;
    public int radius = 25;
    
    
    public void start() {
        isRunning = true;
        new Thread(this).start();
    }
    
    public void stop() {
        isRunning = false;
    }
    
    public void paint(Graphics g) {
        //Create Graphics2D object, cast g as a Graphics2D
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.ORANGE);
        g2d.fillRect(0, 0, 150, 150);
    
        g2d.setColor(Color.BLACK);
        g2d.drawOval((150/2 - radius), (150/2 - radius), radius * 2, radius * 2);
    }
    
    public void run() {
    
        while (isRunning) {
            repaint();
            try {
                Thread.sleep(17);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    }