LoginSignup
8
6

More than 3 years have passed since last update.

swingの中にprocessingを埋め込む

Last updated at Posted at 2015-11-02

まえがき

ずっとProcessingにcomponentが貼り付けられない(理由は後述)ことを嘆いていましたが、

気づいたら一瞬(2日)でした。

注意

swingベースのソフト開発を想定しているのでprocessingIEDで動かすためのコードではありません。
javaのIDEに
EclipseでProcessingを動かす
等を参考にしてprocessingのライブラリをインポートしておいて下さい。

コード

Window.java
import java.awt.Canvas;
import java.awt.Graphics2D;
import javax.swing.*;
import processing.core.PApplet;
import processing.core.PSurface;


public class Window{
  Graphics2D g2;
  public static void main(String[] args){
    Window window=new Window();
  }
  Window(){
    JFrame frame =new JFrame();
    frame.setSize(400,400);
    PApplet second=new Applet(frame);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }

public class Applet extends PApplet {
  JFrame frame;
  Applet(JFrame frame) {
    super();
    //this.frame=frame;
    try {
      java.lang.reflect.Method handleSettingsMethod =
        this.getClass().getSuperclass().getDeclaredMethod("handleSettings", null);
      handleSettingsMethod.setAccessible(true);
      handleSettingsMethod.invoke(this, null);
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      PSurface surface = super.initSurface();
      Canvas canvas=(Canvas)surface.getNative();
      surface.placeWindow(new int[]{0, 0}, new int[]{0, 0});
      frame.add(canvas);
      frame.add(new JButton());
      //this.showSurface();
      this.startSurface();
    }

    public void settings(){
      size(300, 300);
    }
    public void setup(){
      background(0, 0, 0);
      smooth();
      strokeWeight(5);
    }
    public void draw(){
      noStroke();
      fill(0,10);
      rect(0,0,width,height);
      stroke(255);
      if (mousePressed) {
        line(mouseX,mouseY,pmouseX,pmouseY);
      }
    }
  }
}

追記

PApplet.main(new String[] {"クラス名"});を使わなかった理由

showSurface();が呼ばれると、setupでsetVisible(false);を呼ぶとしても一瞬はprocessingのwindowが表示されてしまうからです。

Processing3にcomponentが貼り付けられない理由

processing3は描画にcanvasを使っています。そのcanvasの仕様として上に重なって表示されるコンポーネントは描画されないっからぽい(?)swingです。

参考

Processing 3.0 beta で複数ウィンドウ
eclipseでprocessingを動かす

8
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6