Swing Components in Default Processing Window_py5

Made the minimum required changes to your latest code so it runs on Processing 3 as well: :wink:

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

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

int diameter = 150;
Color dotColor = Color.GREEN;

void colorBtn(int x, int y, int w, int h) {
  JButton btn = new JButton("Color");
  btn.setBounds(x, y, w, h);
  frame.add(btn);
  btn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
      dotColor = JColorChooser.showDialog(null, "Choose color", Color.GREEN);
    }
  }
  );
}

void sizeSlider(int x, int y, int w, int h) {
  // orientation, min, max, value
  final JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 450, 150);
  slider.setBounds(x, y, w, h);
  frame.add(slider);
  println(frameCount);
  slider.addChangeListener(new ChangeListener() {
    public void stateChanged(ChangeEvent changeEvent) {
      diameter = slider.getValue();
    }
  }
  );
}

void buildWnd() {
  sizeSlider(180, 20, 200, 24);
  colorBtn(390, 20, 80, 24);
  frame.setVisible(true);
}

void setup() {
  size(700, 600); // Makes it possible to use draw();
  frame = (javax.swing.JFrame) ((processing.awt.PSurfaceAWT.SmoothCanvas) surface.getNative()).getFrame();
  canvas = (processing.awt.PSurfaceAWT.SmoothCanvas) ((processing.awt.PSurfaceAWT)surface).getNative();
  frame.setBounds(900, 300, width, height); // Makes it possible to add swing components
  frame.setLayout(null);
  canvas.setBounds(0, 60, width, height-60); // For use with draw()
  javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      buildWnd(); // Builds components on EventDispatchThread
    }
  }
  );
}

void draw() {
  background(209);
  fill(dotColor.getRed(), dotColor.getGreen(), dotColor.getBlue());
  stroke(0);
  strokeWeight(2.0);
  circle(width/2, height/2 - 50, diameter);
}

Basically replaced the lambda -> thin arrow syntax w/ a new Runnable callback.

Also replaced _wndW & _wndH w/ width & height respectively, so no settings() callback is required for size().

And lastly, added keywords public & final where they were required for the listeners’ callbacks.

1 Like