Skillversitas

Using the Swing GUI Library

Swing is Java's classic GUI toolkit, and in Jython it is just another import: java.awt and javax.swing. A Python script can open windows, add buttons and labels, and handle events - a full desktop app with no Java boilerplate beyond the toolkit calls.

A Minimal Window

from javax.swing import JFrame, JLabel
import javax.swing.SwingUtilities as su

frame = JFrame("Jython Demo")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.add(JLabel("Hello from Jython", JLabel.CENTER))
frame.setSize(320, 120)
frame.setLocationRelativeTo(None)
frame.setVisible(True)

# for a long-lived app you typically block on the event thread:
# su.invokeLater(frame.setVisible, True)

A Button and a Counter

from javax.swing import JFrame, JButton, JLabel
from java.awt import FlowLayout

class CounterFrame(JFrame):
    def __init__(self):
        self.__init__()  # Java constructor call
        self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        self.setLayout(FlowLayout())
        self.count = 0
        self.label = JLabel("count: 0")
        self.add(self.label)
        btn = JButton("Click me")
        btn.addActionListener(self.on_click)
        self.add(btn)
        self.setSize(320, 100)
        self.setLocationRelativeTo(None)

    def on_click(self, event):
        self.count += 1
        self.label.setText("count: " + str(self.count))

import javax.swing.SwingUtilities as su
su.invokeLater(CounterFrame().setVisible, True)
import time
time.sleep(10)  # keep the script alive while the window is open

Note the __init__ pattern: Jython classes that extend Java classes call the Java no-arg constructor explicitly with self.__init__().

Common Swing Components

ComponentPurpose
JFrametop-level window
JLabeltext/image display
JButtonclickable button
JTextField / JTextAreasingle-line / multi-line input
JCheckBox / JRadioButtontoggles
JComboBoxdropdown selection
JTablegrid of cells
JScrollPanescrollable container

Swing Threading Rules

  • Create and modify Swing components on the Event Dispatch Thread (EDT) - use su.invokeLater for startup and su.invokeLater for updates from other threads.
  • Long work should run in a worker thread (java.util.concurrent or Python threading) and update the UI via invokeLater.

Summary

Swing in Jython is plain Java import plus Python structure: build JFrame windows, add JButton/JLabel/JTextField components, and respond to events with Python methods. Remember the two Jython/Java conventions - call self.__init__() in subclass constructors and keep UI work on the EDT with SwingUtilities.invokeLater.