Skip to content
Tutorials Center
My learning

Topics

Lesson 149 of 201 ยท Desktop GUI

Swing Components - Tables, Lists, Trees and Dialogs

Learn the Swing data components JTable, JList, JComboBox and JTree, how their models work, plus JOptionPane dialogs and menus, with runnable model examples.

Text fields and buttons only get you so far. Real desktop programs show collections of data: a table of orders, a list of files, a tree of folders, a drop-down of countries. Swing has a ready-made component for each, and they all share one idea that is worth understanding before you write any code: the component does not hold the data.

This lesson covers JTable, JList, JComboBox and JTree, the model that sits behind each of them, then JOptionPane dialogs and menus. Our server has no screen or fonts, so complete windows are read-only here. The runnable examples work with the real models, selection models and events, which is where most of the logic lives anyway, and they run the same way in a real application.

The model-view idea

Swing follows a model-view design (often called MVC). Each data component has two parts:

  • The model owns or reads the data and tells listeners when it changes (TableModel, ListModel, TreeModel, ComboBoxModel).
  • The view, the JTable, JList and so on, draws whatever the model says and asks it again after every change event.

A second model, the selection model, tracks which rows or nodes the user picked. That split gives you three useful abilities:

  • Several views can share one model, and all of them update when it changes.
  • You can replace the data source (a list in memory, a database query) without touching the view.
  • Your logic can be tested without any window, as the examples below show.

The DefaultListModel, DefaultTableModel, DefaultTreeModel and DefaultComboBoxModel classes are ready-to-use implementations. For tables with your own data classes, you usually write a model yourself.

JTable and TableModel

A JTable shows rows and columns. Give it a TableModel that answers four questions: how many rows, how many columns, what is the value at (row, column), and what are the column names. AbstractTableModel handles the listeners, so you implement only those. Two more methods are important in practice:

  • getColumnClass(column) lets JTable pick a renderer: Boolean gets a check box, numbers are right-aligned.
  • isCellEditable(row, column) plus setValueAt(...) decide what the user can change. After a change, you must tell the table with a fire... method such as fireTableCellUpdated(row, column) or fireTableRowsInserted(first, last); the view repaints only the parts you announce.

A TableRowSorter adds sorting and filtering to the view without touching the model, and that creates one trap: row numbers in the view are not the model's row numbers once you sort or filter. Always convert with table.convertRowIndexToModel(viewRow). This example uses a book model backed by a Java record, with a listener, a check box column, a sorter and a filter:

Java A TableModel with events, sorting and filtering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the three INSERT events fired as the books were added, and the UPDATE event with column 3 after setValueAt. Those events are what make a real table repaint. With the sorter active, view row 0 is model row 1 (Emma, 1815): the sorted view and the model disagree about row numbers, which is exactly why convertRowIndexToModel exists. Also note that JTable.setValueAt does not check isCellEditable itself: the table's cell editors do that when the user edits, so your own code is trusted to know better.

The window code for a table is short, because the table does the rest:

Java
JTable table = new JTable(model);
table.setAutoCreateRowSorter(true);                 // click a header to sort
table.setFillsViewportHeight(true);                 // paint the empty area below the rows
frame.add(new JScrollPane(table));                  // a table has no scroll bars of its own

Always put a JTable, JList and JTree inside a JScrollPane; without it you don't even see the column headers.

For quick prototypes, new DefaultTableModel(columnNames, rowCount) and model.addRow(Object[]) need no custom class, but everything is stored as Object, so you lose type safety and sorting by number. For anything that stays in your program, a small model class like the one above is better.

JList and ListModel

JList<E> shows a column of items. Its ListModel<E> has just getSize(), getElementAt(index) and a way to add listeners. DefaultListModel<E> is a mutable implementation, with addElement, add(index, e), set, remove..., and it fires ListDataEvents for you. Passing a plain array or Vector to the JList constructor creates a read-only model, which is fine for fixed lists.

Selection is a separate object, a ListSelectionModel, with three modes: SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION (one contiguous range) and MULTIPLE_INTERVAL_SELECTION (Ctrl and Shift clicks). The listener fires twice during a mouse drag: once with getValueIsAdjusting() true while the user is still dragging, and once when they stop. Ignore the adjusting events or your handler will run too often.

A JComboBox<E> is the drop-down version: it uses a ComboBoxModel, which is a list model that also remembers the selected item. Use setEditable(true) to let the user type a value that is not in the list.

Java List, selection and combo box models

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The list events carry index ranges: when "eggs" is inserted at index 1, the event says added 1..1, and set(0, ...) reports changed 0..0. A view uses those numbers to repaint only the affected rows. In the selection model, getLeadSelectionIndex() is the most recently clicked row and getMinSelectionIndex() is the first selected one. The combo box model fires a "contents changed" event when the selection changes, which is also how a real JComboBox knows to redraw and to fire its own ActionEvent.

In a window you would write:

Java
JList<String> list = new JList<>(items);
list.addListSelectionListener(e -> {
    if (!e.getValueIsAdjusting()) {
        status.setText("Selected: " + list.getSelectedValuesList());
    }
});
frame.add(new JScrollPane(list));

Custom appearance comes from a cell renderer: a ListCellRenderer that returns the component used to paint each row (for example a label with an icon). The same idea applies to tables (TableCellRenderer) and trees (TreeCellRenderer). The renderer is only a stamp: Swing reuses one component to paint every row, so never store state in it.

JTree and TreeModel

A JTree displays hierarchical data: folders, a menu structure, an organisation chart. The usual model is DefaultTreeModel holding DefaultMutableTreeNode objects. Each node has a user object (anything, shown with toString()), a parent and children. A TreePath identifies one node as the list of nodes from the root, and the selection model works in paths.

Always change a tree through its model (insertNodeInto, removeNodeFromParent, nodeChanged) rather than calling node.add(...) after the tree is on screen. Only the model methods send the events that make the tree update.

Java A tree model, paths and events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

depthFirstEnumeration() is post-order, children before their parent, which is the right order for deleting or summing a subtree; preorderEnumeration() and breadthFirstEnumeration() are available too. The TreeModelEvent carries the path of the parent whose children changed.

Trees can also be built lazily: a TreeWillExpandListener or a custom TreeModel can load the children of a folder only when the user expands it. For a large tree such as a file system, loading everything at once would be slow, so this is the usual approach.

Dialogs with JOptionPane

Small questions do not deserve a custom window. JOptionPane offers static methods that show a modal dialog (it blocks interaction with the rest of the program until closed) and return the user's answer:

Method Use Returns
showMessageDialog(parent, message, title, type) Tell the user something nothing
showConfirmDialog(parent, message, title, optionType) Yes/No/Cancel YES_OPTION, NO_OPTION, CANCEL_OPTION, CLOSED_OPTION
showInputDialog(parent, message) Ask for one line of text the String, or null if cancelled
showOptionDialog(...) Custom button labels index of the chosen button

The message type (ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE) picks the icon. Pass the parent frame so the dialog is centered over it. These calls need a screen, so here they are read-only:

Java
int answer = JOptionPane.showConfirmDialog(frame,
        "Delete 3 files? This cannot be undone.", "Confirm delete",
        JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (answer == JOptionPane.YES_OPTION) {
    deleteFiles();
}

String name = JOptionPane.showInputDialog(frame, "Name of the new folder:");
if (name != null && !name.isBlank()) {          // null means the user pressed Cancel
    createFolder(name.strip());
}

Always handle the cancel case. For file selection use JFileChooser, for colors JColorChooser. For anything more complex, build a JDialog with its own layout.

A menu bar is a tree of ordinary components: a JMenuBar holds JMenus, and a JMenu holds JMenuItems, JCheckBoxMenuItems, JRadioButtonMenuItems, separators and nested menus. Menu items are buttons, so they use the same ActionListener (or a shared Action, as in Swing Events) and have setAccelerator for shortcuts like Ctrl+O and setMnemonic for Alt+F style access.

Java Building a menu bar

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The menu structure works without a window, and doClick() triggers an item the same way a user's click does; the check box item toggles its selected state automatically. To show it in a real window you call frame.setJMenuBar(bar). Pop-up (context) menus use JPopupMenu the same way, shown with popup.show(component, x, y) from a mouse listener.

Common mistakes

  • Forgetting the JScrollPane. Tables, lists and trees need one to show scroll bars (and table headers).
  • Changing the data without firing an event. If you edit a list behind the model's back, the view shows stale data. Always go through the model or call the right fire... method.
  • Mixing up view and model indexes after sorting or filtering (convertRowIndexToModel).
  • Doing slow work in a renderer or model method. They run for every visible cell on every repaint, on the event dispatch thread. Keep them quick.
  • Updating a component from another thread. Use SwingUtilities.invokeLater or SwingWorker, as shown in Swing Events.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Swing separate JTable from its TableModel?

    The view only displays what the model reports, and it redraws when the model announces a change. That keeps data logic separate from drawing, so it is reusable and testable.
  2. 2. Your table model changes a value in its internal list, but the table still shows the old value. What is missing?

    Views only update after they receive a TableModelEvent. AbstractTableModel provides the fire... methods for each kind of change.
  3. 3. A sorted JTable shows "Emma" in view row 0. Which call gives the row of that book in the model?

    With a RowSorter active, view and model rows differ. convertRowIndexToModel translates a view row to the matching model row.
  4. 4. What does JOptionPane.showInputDialog return when the user presses Cancel?

    A cancelled input dialog returns null, which differs from an empty string, so always test for null before using the result.
  5. 5. Which is the correct way to add a node to a visible JTree?

    DefaultTreeModel.insertNodeInto changes the node structure and notifies the tree. Changing the nodes directly leaves the view out of date.

Summary

  • Swing data components keep model and view apart: TableModel, ListModel, ComboBoxModel and TreeModel hold the data; JTable, JList, JComboBox and JTree display it; selection models track what is chosen.
  • After you change data, fire the matching event (fireTableRowsInserted, ListDataEvent, insertNodeInto) so the view repaints.
  • TableRowSorter sorts and filters the view only; convert indexes with convertRowIndexToModel.
  • Put tables, lists and trees in a JScrollPane, ignore getValueIsAdjusting() selection events, and keep renderers cheap and stateless.
  • JOptionPane gives quick modal message, confirm and input dialogs; always handle cancel and null.
  • Menus are trees of JMenuBar, JMenu and JMenuItem objects with accelerators, mnemonics and ordinary action listeners.

Next: JavaFX Introduction, the modern alternative to Swing, with stages, scenes, properties and binding.