Swing Components in Default Processing Window_py5

A more Java-ish version using this = py5._instance, so it’ more in line w/ both Java & Processing’s API lowerCamelCase naming convention: :coffee:

"""
 * py5 Swing Demo (v1.0.0)
 * GoToLoop & Svan (2024/May/25)
 *
 * https://Discourse.Processing.org/t/
 * swing-components-in-default-processing-window-py5/3
"""

import py5

from java.awt.Color import GREEN
from javax.swing import JSlider, JLabel, JButton, JColorChooser

DIAM = 'Diameter: %d'

this = py5._instance
fill = GREEN

def settings(): this.size(600, 660)

def setup():
    this.noLoop()
    this.fill(fill.getRGB())

    global cx, cy, slider, label

    w, h = this.width, this.height
    cx, cy = w >> 1, h >> 1

    slider = JSlider(0, w - 60, cx)
    slider.setBounds(180, 20, 200, 24)
    slider.addChangeListener(slideChange)
    slider.setToolTipText('circle diameter')

    (label := JLabel(DIAM % cx)).setBounds(75, 20, 80, 24)

    btn = JButton('Color')
    btn.setBounds(400, 20, 80, 24)
    btn.addActionListener(btnAction)

    (window := this.getSurface()).setTitle('py5 Swing Demo')
    (canvas := window.getNative()).setBounds(0, 60, w, h - 60)

    frame = canvas.getFrame()
    frame.add(slider); frame.add(label); frame.add(btn)
    slider.repaint(); label.repaint(); btn.repaint()


def draw():
    this.background(0o320)
    this.circle(cx, cy, slider.getValue())


def mouse_wheel(e): slider.setValue(slider.getValue() - e.get_count() * 10)

def slideChange(_):
    label.setText(DIAM % slider.getValue())
    this.redraw()


def btnAction(_, TITLE = 'Choose color:'):
    global fill
    fill = JColorChooser.showDialog(None, TITLE, fill) or fill

    this.fill(fill.getRGB())
    this.redraw()


__name__ == '__main__' and py5.run_sketch()
1 Like