Mixing Processing and Swing


#1

I’ve read through the Swing and Processing as a Java Library tutorials, and I’m trying to combine the two to create a Swing application that contains a Processing sketch.

I’ve tried this:

import javax.swing.JFrame;
import processing.core.PApplet;

  public class MySketch extends PApplet{
	
	public void settings(){
		size(500, 500);
	}
	
	public void draw(){
		background(255, 0, 0);
		fill(0, 255, 0);
		ellipse(width/2, height/2, width, height);
	}
	
	public static void main(String[] args){
		JFrame frame = new JFrame("Processing Example");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		//The method add(Component) in the type Container is not applicable for the arguments (MySketch)
		frame.add(new MySketch());
		
		frame.setSize(500,  500);
		frame.setVisible(true);
	}
}

But I get an error saying The method add(Component) in the type Container is not applicable for the arguments (MySketch)

How can I add a Processing sketch into a Swing application?


#2

You used to be able to do what you’re trying to do in Processing 2, but they got rid of it in Processing 3. You can read more about that here, but basically they stopped supporting this when Java applets were discontinued.

You have three options:

  • You can mix Swing and Processing, but you’ll probably want to keep them in different windows. I’ve put together an example here:
  • You could also use a Processing GUI library like ControlP5 of G4P.

  • If you really really really need to embed Processing as a component, you could go back to using Processing 2. But I don’t recommend that.