Skip to main content

Coming from Swing

Open in ChatGPT

This page maps the concepts of a Java Swing desktop app to their webforJ counterparts. In both, the UI is plain Java: components are Java objects, events are handled by listeners, and layouts are composed in code. webforJ runs on the server, and the framework keeps the browser in sync with the component state. See Component architecture for how that works.

The webforJ API is analogous to Swing, not compatible with it. Each screen is rewritten against the webforJ API, while classes that don't depend on javax.swing or java.awt, such as services, entities, and validation rules, are called from the new views unchanged.

Windows and frames​

A Swing app creates a JFrame, adds content, and shows it. In webforJ, the browser page is the window. The app class extends App, and the framework provides a Frame that holds the visible content. With routing enabled through @Routify, each screen is a class annotated with @Route, and the router renders it into the frame.

SwingwebforJReference
JFrameApp and Frame, with screens as @Route classesRoutable apps, Routing
JFrame.setTitle@FrameTitle or HasFrameTitleNavigational frame titles
Main method that builds the UIApp subclass with @RoutifyApp basics

Panels and layout managers​

A JPanel with a layout manager becomes a Composite bound to a layout component. FlexLayout arranges children in a row or a column, with spacing, alignment, and wrapping, and covers most screens built with BoxLayout or FlowLayout. A BorderLayout window shell maps to AppLayout, and other BorderLayout panels to nested FlexLayout containers.

SwingwebforJReference
JPanel subclassComposite<T> bound to a container such as FlexLayout or DivComposing components
BoxLayout, FlowLayoutFlexLayoutFlexLayout
BorderLayoutAppLayout for a window shell, nested FlexLayout containers for other panelsAppLayout, FlexLayout
GridLayout, GridBagLayout formsColumnsLayoutColumnsLayout
JSplitPaneSplitterSplitter
JTabbedPaneTabbedPaneTabbedPane
JToolBarToolbarToolbar
Main window with header, side menu, and content areaAppLayoutAppLayout

A Swing panel with a text field and a button that reacts to clicks becomes the following view:

@Route("customers/new")
@FrameTitle("New customer")
public class NewCustomerView extends Composite<FlexLayout> {
private final FlexLayout self = getBoundComponent();
private final TextField name = new TextField("Name");
private final Button save = new Button("Save", ButtonTheme.PRIMARY);

public NewCustomerView() {
self.setDirection(FlexDirection.COLUMN).setSpacing("1em");
save.onClick(e -> OptionDialog.showMessageDialog("Saved " + name.getValue(), "Customer"));
self.add(name, save);
}
}

Components​

Most Swing components have a direct counterpart. Text components use setText() for their caption and input components use getValue() and setValue() for their content, as described in Using components.

SwingwebforJReference
JButtonButtonButton
JLabelLabelUsing components
JTextFieldTextFieldTextField
JPasswordFieldPasswordFieldPasswordField
JFormattedTextFieldMaskedTextField and the other masked fieldsMaskedTextField
JTextAreaTextAreaTextArea
JCheckBoxCheckBoxCheckBox
JRadioButton and ButtonGroupRadioButton and RadioButtonGroupRadioButton, RadioButtonGroup
JComboBoxChoiceBox for a fixed set, ComboBox when users can type a valueChoiceBox, ComboBox
JListListBoxListBox
JTreeTreeTree
JProgressBarProgressBarProgressBar
JSliderSliderSlider

Listeners and events​

Swing registers listeners with addXxxListener methods. webforJ components expose the same pattern: an addXxxListener method and, in most cases, a shorter on alias. Each registration returns a ListenerRegistration, and calling remove() on it replaces Swing's removeXxxListener. See Events.

SwingwebforJReference
ActionListener on a buttononClick or addClickListenerButton
DocumentListener on a text fieldonModifyEvents
ItemListener on a JCheckBoxonToggleCheckBox
ChangeListener and property change listeners on valuesonValueChangeEvents
FocusListeneronFocus and onBlurEvents
KeyListener on a fieldonKeypressEvents
removeXxxListenerListenerRegistration.remove()Removing an event

The event dispatch thread and UI updates​

Swing requires all UI work on the event dispatch thread. webforJ has the same rule: each user session has an Environment thread, and all UI updates must happen on it. Constructors, event handlers, and lifecycle methods already run there. A background thread must hand its UI changes back with Environment.runLater(Environment, Runnable).

Read the target with Environment.getCurrent() on the Environment thread, before the background work starts. On a background thread, getCurrent() returns null. See Asynchronous updates for the thread model and task cancellation through PendingResult.

SwingwebforJReference
Event dispatch threadEnvironment thread of the sessionAsynchronous updates
SwingUtilities.invokeLaterEnvironment.runLater(Environment, Runnable)Asynchronous updates
SwingWorkerBackground work, for example CompletableFuture, then Environment.runLaterAsynchronous updates
javax.swing.TimerIntervalInterval
Restarting a timer on every keystrokeDebouncerDebouncing

The doInBackground body of a SwingWorker becomes the background task, and the done method becomes the runLater blocks, one for the result and one for a failure:

public class ReportView extends Composite<FlexLayout> {
private final FlexLayout self = getBoundComponent();
private final CustomerService service = new CustomerService();
private final Button export = new Button("Export");
private final Label status = new Label();

public ReportView() {
self.add(export, status);
export.onClick(e -> {
Environment env = Environment.getCurrent();
CompletableFuture.supplyAsync(service::exportReport)
.thenAccept(path -> Environment.runLater(env, () -> { status.setText("Saved to " + path); }))
.exceptionally(error -> {
Environment.runLater(env, () -> { status.setText("Export failed"); });
return null;
});
});
}
}

Models and data binding​

Swing separates data from views with model interfaces such as TableModel and ListModel, and code that copies values between fields and objects by hand. webforJ uses a Repository as the data source for components such as Table, and a BindingContext to connect form fields to bean properties in both directions.

SwingwebforJReference
TableModelRepository, such as CollectionRepositoryRepository
ListModelListItem entries added to a ListBox, ChoiceBox, or ComboBoxLists
fireTableDataChanged, fireTableRowsUpdatedcommit() and commit(entity) on the repositoryData synchronization
Copying field values to and from an objectBindingContext with read(bean) and write(bean)Data binding, Automatic binding
InputVerifierValidators on bindings, or Jakarta ValidationValidation, Jakarta Validation

BindingContext.of binds component fields to bean properties with the same name:

public class CustomerForm extends Composite<FlexLayout> {
private final FlexLayout self = getBoundComponent();
private final TextField name = new TextField("Name");
private final TextField email = new TextField("Email");
private final BindingContext<Customer> context;

public CustomerForm(Customer customer) {
self.setDirection(FlexDirection.COLUMN).add(name, email);
context = BindingContext.of(this, Customer.class);
context.read(customer);
}

public boolean save(Customer customer) {
return context.write(customer).isValid();
}
}

Dialogs​

Option dialogs are modal and block execution until the user responds, like JOptionPane. The code after the call reads the result directly, with no callback. See Option dialogs.

SwingwebforJReference
JOptionPane.showMessageDialogOptionDialog.showMessageDialogMessage dialog
JOptionPane.showConfirmDialogOptionDialog.showConfirmDialog, returning ConfirmDialog.ResultConfirm dialog
JOptionPane.showInputDialogOptionDialog.showInputDialogInput dialog
JFileChooser for opening a file on the user's machineOptionDialog.showFileUploadDialogFile upload dialog
JFileChooser for browsing server filesOptionDialog.showFileChooserDialogFile chooser dialog
JDialog with custom contentDialog, opened with open() and closed with close()Dialog
ConfirmDialog.Result result = OptionDialog.showConfirmDialog(
"Delete this customer?", "Delete customer",
ConfirmDialog.OptionType.YES_NO, ConfirmDialog.MessageType.QUESTION);

if (result == ConfirmDialog.Result.YES) {
service.delete(customer);
}

Tables​

A JTable reads from a TableModel subclass. A webforJ Table<T> holds a list of entities and binds each column to a getter, so there is no model class to write. setItems wraps a collection in a repository, and setRepository accepts one backed by your data layer. See Table.

SwingwebforJReference
JTable with a TableModelTable<T> with setItems or setRepositoryTable
TableColumn and getValueAtaddColumn(id, getter)Columns
ListSelectionModelsetSelectionMode, getSelectedItems, onItemSelectSelection
MouseListener checking for a double clickonItemDoubleClickTable
TableRowSorterColumn.setSortable(true)Sorting
RowFiltersetBaseFilter(Predicate) on a CollectionRepository, applied when you call commit()Filtering
TableCellRendererRenderer set with Column.setRendererRendering
Table<Customer> table = new Table<>();
table.addColumn("Name", Customer::getName);
table.addColumn("Email", Customer::getEmail);
table.setSelectionMode(Table.SelectionMode.SINGLE);
table.setItems(service.findAll());
table.onItemDoubleClick(e -> confirmDelete(e.getItem()));

Swing apps switch screens by swapping panels, often with CardLayout, or by opening new windows. In webforJ each screen is a route with its own URL, so browser history, bookmarks, and deep links work. See Routing.

SwingwebforJReference
CardLayout.show or replacing the content panel@Route views and Router.getCurrent().navigate(View.class)Defining routes, Route navigation
JMenu or a side list of screensAppNav with AppNavItem entries linked to routesAppNav
Opening a screen with parametersRoute parameters and query parametersRoute patterns, Query parameters
Router.getCurrent().navigate(NewCustomerView.class);

Moving screen by screen​

The Swing app doesn't have to be rewritten in one pass. Webswing runs an existing Swing, JavaFX, or SWT app in the browser without changes to its source, and the WebswingConnector component embeds it inside a webforJ view. Only two-way messages need a small addition to the Swing app, described below. Old and new screens then live in one app while screens move over one at a time.

The connector is two-way. performAction sends actions from webforJ to the Swing app, and onAction receives actions the Swing app sends through the Webswing Java API. Sending actions back requires adding that API to the Swing app.

On the Swing side, the webswing-api dependency from the Webswing repository provides WebswingUtil.getWebswingApi(). It returns null when the app runs as a regular desktop app, so the same code keeps working on the desktop. Here double-clicking a table row sends the selected customer to webforJ instead of opening a Swing dialog:

WebswingApi api = WebswingUtil.getWebswingApi();

if (api != null) {
api.sendActionEvent("select-customer", gson.toJson(customer), null);
} else {
showEditDialog(customer);
}

Keep learning