Dialogs
Dialogs are small windows for focused interaction: messages, confirmations, and input prompts. Swing offers JOptionPane for the standard prebuilt dialogs (message, yes/no, input) and JDialog/JFrame for custom dialog layouts. In Jython both are straightforward Java API usage.
Message Dialogs
from javax.swing import JOptionPane, JFrame
frame = JFrame("Dialogs")
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
frame.setSize(300, 150)
frame.setVisible(True)
# informational
JOptionPane.showMessageDialog(frame, "Operation complete.")
# warning
JOptionPane.showMessageDialog(
frame, "Disk almost full.", "Warning",
JOptionPane.WARNING_MESSAGE)
# error
JOptionPane.showMessageDialog(
frame, "File not found.", "Error",
JOptionPane.ERROR_MESSAGE)
Yes/No and Option Dialogs
reply = JOptionPane.showConfirmDialog(
frame, "Save changes before closing?",
"Unsaved changes",
JOptionPane.YES_NO_CANCEL_OPTION)
if reply == 0: # YES_OPTION
print("save")
elif reply == 1: # NO_OPTION
print("discard")
else:
print("cancel")
choice = JOptionPane.showOptionDialog(
frame, "Pick an action", "Action",
0, 1, None,
["Import", "Export", "Cancel"], "Import")
Input Dialog
name = JOptionPane.showInputDialog(
frame, "Your name:", "Greeting", "Ada")
if name:
JOptionPane.showMessageDialog(frame, "Hello, " + name + "!")
A Custom Dialog
from javax.swing import (JDialog, JTextField, JButton,
JOptionPane, GridLayout)
from java.awt import GridBagLayout, GridBagConstraints
import java.awt as awt
def make_login_dialog(parent):
dlg = JDialog(parent, "Login", True) # modal
dlg.setLayout(GridBagLayout())
g = GridBagConstraints()
g.insets = awt.Insets(4, 4, 4, 4)
user_field = JTextField(14)
pass_field = JTextField(14)
pass_field.setEchoChar("*")
g.gridx, g.gridy = 0, 0
dlg.add(awt.Label("User:"), g)
g.gridx = 1
dlg.add(user_field, g)
g.gridx, g.gridy = 0, 1
dlg.add(awt.Label("Pass:"), g)
g.gridx = 1
dlg.add(pass_field, g)
result = {"ok": False}
def on_ok(e):
if user_field.getText() and pass_field.getText():
result["ok"] = True
dlg.dispose()
ok = JButton("OK")
ok.addActionListener(on_ok)
g.gridx, g.gridy = 0, 2
g.gridwidth = 2
dlg.add(ok, g)
dlg.pack()
dlg.setLocationRelativeTo(parent)
dlg.setVisible(True)
return result["ok"], user_field.getText(), pass_field.getText()
# usage:
# ok, u, p = make_login_dialog(frame)
Modal vs Modeless
- Modal (JOptionPane dialogs, JDialog(..., True)): blocks the parent until dismissed - use for required decisions.
- Modeless (JDialog(..., False)): coexists with the parent - use for tool windows and inspectors.
Summary
Use JOptionPane for standard dialogs - showMessageDialog for info/warn/error, showConfirmDialog and showOptionDialog for choices, showInputDialog for quick text input - and build custom modal or modeless JDialogs with the same layout managers and listeners as any window. Modality is the key decision: block the parent only when the user must answer before continuing.