Java2D Graphics in Default Processing Canvas

The following source code demonstrates Java2d graphics on the default Processing canvas using Java’s Class BufferStrategy, documented here: https://docs.oracle.com/javase/8/docs/api/java/awt/image/BufferStrategy.html . The demo works only with the default renderer and supports Graphics as well as Graphics2D. It is run from Processing’s setup() in this demo and may also be run from the draw() loop, but experiences occasional flickers when using the latter technique. Processing’s draw() is non-functional when using the technique below.

//https://docs.oracle.com/javase/8/docs/api/java/awt/image/BufferStrategy.html
//For use with default renderer only.

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;

javax.swing.JFrame frame;
java.awt.Canvas canvas;

Graphics g;
Graphics2D g2d;

BufferStrategy bufferStrategy;

int _wndW = 600;
int _wndH = 600;

void setup() {
  size(_wndW, _wndH);
  surface.setTitle("Java2D Graphics on Default AWT Canvas");
  frame = (javax.swing.JFrame) ((processing.awt.PSurfaceAWT.SmoothCanvas) surface.getNative()).getFrame();
  canvas = (processing.awt.PSurfaceAWT.SmoothCanvas) ((processing.awt.PSurfaceAWT)surface).getNative();
  frame.setBounds(100, 100, _wndW, _wndH);
  canvas.setBounds(0, 50, _wndW, _wndH - 50); // Position default canvas lower to make room for controls
  canvas.setBackground(Color.WHITE);
  canvas.createBufferStrategy(3);

  boolean running = true;
  while (running) {
    bufferStrategy = canvas.getBufferStrategy();
    g = bufferStrategy.getDrawGraphics();
    g2d = (Graphics2D) g;

    g2d.clearRect(0, 0, width, height);
    // **** Text **** //
    Font txtFont = new Font("Monospaced", Font.BOLD, 18);
    g2d.setFont(txtFont);
    g2d.setColor(Color.BLUE);
    g2d.drawString("JAVA2D -- text placed at top left corner.", 15, 35);
    // **** Rectangle2D **** //
    g2d.setPaint(Color.BLACK);
    g2d.setStroke( new BasicStroke(4));
    Rectangle2D rect = new Rectangle2D.Double(60, 100, 200, 100);
    g2d.draw(rect);
    // **** Ellipse2D **** //
    Ellipse2D ellipse = new Ellipse2D.Double();
    ellipse.setFrame(rect);
    g2d.draw(ellipse);
    // **** Line2D **** //
    Line2D line = new Line2D.Double(60, 100, 260, 200);
    g2d.draw(line);

    g2d.setPaint(Color.BLUE);
    g2d.drawRoundRect(450, 150, 75, 45, 15, 15);
    int[] x = {400, 450, 450, 400, 350, 350};
    int[] y = {250, 275, 325, 350, 325, 275};
    g2d.drawPolygon(x, y, 6);
    g.setColor(Color.RED);
    g.fillRect(330, 120, 100, 80);
    g.drawOval(30, 230, 50, 60);
    g.fillOval(130, 230, 50, 60);
    g2d.setStroke( new BasicStroke(10));
    g.setColor(Color.GREEN);
    g.drawArc(150, 200, 140, 170, -30, 60);
    g.fillArc(30, 230, 40, 50, 180, 40);
    g2d.setColor(Color.magenta);
    g2d.drawLine(60,400,540,400);
    bufferStrategy.show();
    g.dispose();
  }
}

Output:

2 Likes