How do I filter rows in a JTable in Java Swing?

Use a TableRowSorter with a RowFilter to show only the rows that match a condition. The filter changes which rows are visible while keeping all the data in the table model.

In this example, typing in a search field filters a book catalog by title. The search ignores letter case and updates as you type.

Source code

Save the following code as TableFilterExample.java:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

public class TableFilterExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        String[] columns = {"Title", "Author"};
        Object[][] books = {
                {"Learning Java", "Alice"},
                {"Exploring Java", "Bob"},
                {"Building Java Apps", "Carol"}
        };

        DefaultTableModel model = new DefaultTableModel(books, columns) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        JTable table = new JTable(model);
        table.setPreferredScrollableViewportSize(new Dimension(420, 100));

        TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(model);
        table.setRowSorter(sorter);

        JTextField searchField = new JTextField(18);
        searchField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent event) {
                updateFilter();
            }

            @Override
            public void removeUpdate(DocumentEvent event) {
                updateFilter();
            }

            @Override
            public void changedUpdate(DocumentEvent event) {
                updateFilter();
            }

            private void updateFilter() {
                String query = searchField.getText().strip();

                if (query.isEmpty()) {
                    sorter.setRowFilter(null);
                } else {
                    String pattern = "(?iu)" + Pattern.quote(query);
                    sorter.setRowFilter(RowFilter.regexFilter(pattern, 0));
                }
            }
        });

        JLabel label = new JLabel("Filter titles:");
        label.setLabelFor(searchField);

        JPanel searchPanel = new JPanel(new BorderLayout(8, 0));
        searchPanel.add(label, BorderLayout.LINE_START);
        searchPanel.add(searchField, BorderLayout.CENTER);

        JPanel content = new JPanel(new BorderLayout(0, 10));
        content.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
        content.add(searchPanel, BorderLayout.PAGE_START);
        content.add(new JScrollPane(table), BorderLayout.CENTER);

        JFrame frame = new JFrame("Book Catalog");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration of the Book Catalog filtered by exploring, showing only Exploring Java by Bob

Explanation

The TableRowSorter controls which rows the table displays. Calling table.setRowSorter(sorter) connects it to the table. The model still holds all three books, even when the table shows only one.

A DocumentListener reacts to changes in the search field. When the user types, pastes, or deletes text, the listener reads the current query and updates the filter. The user does not need to press Enter.

String pattern = "(?iu)" + Pattern.quote(query);
sorter.setRowFilter(RowFilter.regexFilter(pattern, 0));

The (?iu) flags enable case-insensitive matching with Unicode case rules. Pattern.quote() treats the search text literally, so characters such as . or [ are searched as typed.

The 0 tells the filter to check only the first column in the model, Title. The filter looks for a match anywhere in that column’s text, so exploring matches Exploring Java. To search both titles and authors, pass 0, 1 as the column indexes.

When the search field is empty or contains only whitespace, sorter.setRowFilter(null) clears the filter and shows all rows again.

Run the example

javac TableFilterExample.java
java TableFilterExample

Type exploring to show only Exploring Java. Type java to match all three titles, or clear the search field to remove the filter.

How do I display data in a JTable in Java Swing?

Use a JTable to display data in rows and columns. A table model provides the data, column names, and rules for editing cells.

In this example, you will display a read-only book catalog with three columns: Title, Author, and Pages.

Source code

Save the following code as TableExample.java:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class TableExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        String[] columns = {"Title", "Author", "Pages"};
        Object[][] books = {
                {"Learning Java", "Alice", 240},
                {"Exploring Java", "Bob", 180},
                {"Building Java Apps", "Carol", 320}
        };

        DefaultTableModel model = new DefaultTableModel(books, columns) {
            @Override
            public Class<?> getColumnClass(int column) {
                return column == 2 ? Integer.class : String.class;
            }

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        JTable table = new JTable(model);
        table.setPreferredScrollableViewportSize(new Dimension(420, 120));

        JFrame frame = new JFrame("Book Catalog");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(table));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration of a Book Catalog window with three rows and columns for title, author, and page count

Explanation

Each row in the books array represents one book. The values follow the same order as the column names. The array uses Object[][] because each row contains both text and a number.

DefaultTableModel supplies the rows and column names to JTable. The example overrides two methods:

Method What it does
getColumnClass() Tells Swing that column 2 (the third column) contains Integer values. The first two columns contain String values. Swing uses these types to choose how to display each cell.
isCellEditable() Returns false for every cell, so users can select cells but cannot edit them through the table.

Adding new JScrollPane(table) to the frame displays the column headers and lets users scroll if the rows do not fit. The preferred viewport size gives the table a starting size when frame.pack() sizes the window.

Run the example

javac TableExample.java
java TableExample

The Book Catalog window displays all three books. Try double-clicking a title: the cell can be selected, but it does not open for editing.

How do I create a drop-down list using JComboBox in Java Swing?

Use JComboBox to let the user choose one item from a drop-down list. In this example, selecting a programming language updates a label below the list.

Source code

Save the following code as ComboBoxExample.java:

import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class ComboBoxExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        String[] languages = {"Java", "Python", "Kotlin"};
        JComboBox<String> languageBox = new JComboBox<>(languages);

        JLabel prompt = new JLabel("Choose a language:");
        prompt.setLabelFor(languageBox);

        JLabel selection = new JLabel(
                "Selected: " + languageBox.getSelectedItem(),
                SwingConstants.CENTER);

        languageBox.addActionListener(event ->
                selection.setText(
                        "Selected: " + languageBox.getSelectedItem()));

        JPanel controls = new JPanel();
        controls.add(prompt);
        controls.add(languageBox);

        JPanel content = new JPanel(new BorderLayout(0, 10));
        content.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
        content.add(controls, BorderLayout.PAGE_START);
        content.add(selection, BorderLayout.CENTER);

        JFrame frame = new JFrame("Language Picker");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What the window looks like

Illustration of the Language Picker window with Python selected and the label Selected: Python below it

Explanation

new JComboBox<>(languages) creates a drop-down list from the array. The first item, Java, is selected when the window opens. The list is non-editable by default, so the user chooses from the supplied options.

Use getSelectedItem() to read the current selection. It returns an Object, which you can concatenate directly with a label such as "Selected: ". If there is no selection, it returns null. This example always starts with a selection and offers no way to clear it.

addActionListener() registers code that Swing calls when the user makes a selection. The listener reads the current item and updates the existing label with setText().

Run the example

javac ComboBoxExample.java
java ComboBoxExample

The window opens with Selected: Java. Choose Python from the drop-down list, and the label changes to Selected: Python.

How do I arrange a form using GridBagLayout in Java Swing?

Use GridBagLayout to arrange labels and fields in rows and columns. You can give each component its own position and decide how it should resize.

In this example, the labels stay on the left while the text fields on the right grow wider when you resize the window.

Source code

Save the following code as GridBagLayoutExample.java:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class GridBagLayoutExample {
    void main() {
        SwingUtilities.invokeLater(this::showWindow);
    }

    private void showWindow() {
        JPanel form = new JPanel(new GridBagLayout());

        addRow(form, 0, "Name:");
        addRow(form, 1, "Email:");

        JFrame frame = new JFrame("Contact Form");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(form);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private void addRow(JPanel form, int row, String labelText) {
        JLabel label = new JLabel(labelText);
        JTextField field = new JTextField(20);
        label.setLabelFor(field);

        GridBagConstraints labelConstraints = new GridBagConstraints();
        labelConstraints.gridx = 0;
        labelConstraints.gridy = row;
        labelConstraints.anchor = GridBagConstraints.LINE_START;
        labelConstraints.insets = new Insets(6, 8, 6, 8);
        form.add(label, labelConstraints);

        GridBagConstraints fieldConstraints = new GridBagConstraints();
        fieldConstraints.gridx = 1;
        fieldConstraints.gridy = row;
        fieldConstraints.weightx = 1.0;
        fieldConstraints.fill = GridBagConstraints.HORIZONTAL;
        fieldConstraints.insets = new Insets(6, 8, 6, 8);
        form.add(field, fieldConstraints);
    }
}

What the form looks like

Illustration of the contact form with Name and Email labels on the left and fields that stretch horizontally on the right

Explanation

GridBagLayout places components in an invisible grid. Each call to form.add() passes a component and a GridBagConstraints object that tells Swing how to place it.

Setting What it does in this example
gridx Selects the column: 0 for labels and 1 for fields
gridy Selects the row: 0 for Name and 1 for Email
anchor Aligns the label at the start of its cell
insets Adds space outside each component, in top, left, bottom, right order
weightx Gives the field column the extra horizontal space
fill Lets each field stretch horizontally to use that space

weightx and fill do different jobs. weightx determines which column receives extra width. fill determines whether a component grows to use the width of its cell. Without HORIZONTAL fill, the field could stay at its preferred width even when its column grows.

frame.pack() sizes the window to fit the form at its preferred size. The whole window is created on Swing’s event dispatch thread using invokeLater().

Run the example

javac GridBagLayoutExample.java
java GridBagLayoutExample

The Contact Form window opens with two rows. Drag the right edge outward to see both text fields widen while the labels stay aligned.

How do I scale and paint an image in Swing?

Java Image Tutorials

In the previous post, we chose file formats and exported images. In this example, we will display one image at different sizes, keep its aspect ratio, and compare three interpolation methods. Use JDK 25. The program creates a small sample image, so no input file is required.

Paint inside a component

For custom Swing drawing, extend JPanel and override paintComponent(Graphics). Call super.paintComponent(g) first so the panel can paint its background. Then use a copy of the graphics context and dispose of that copy when finished. Keep the graphics context supplied by Swing intact.

Swing calls the painting method when the component needs updating, including after resizing. When your application changes something that affects its appearance, call repaint() to request another paint. Avoid loading files or performing expensive calculations inside the painting method.

Keep the aspect ratio

Suppose an image is 160 × 100 pixels. Its aspect ratio is 1.6. Stretching it to 300 × 300 would distort the image. To fit it inside an available area, calculate one scale factor for both dimensions:

scale = min(availableWidth / imageWidth, availableHeight / imageHeight)
drawWidth = imageWidth * scale
drawHeight = imageHeight * scale

Use floating-point division. Center the result by dividing the remaining space by two. This leaves empty space above and below, or on the left and right. Integer rounding can introduce a small ratio difference of less than a pixel in a dimension.

Choose interpolation

Interpolation determines how Java 2D samples pixels when drawing at a different size.

Hint value What to look for
VALUE_INTERPOLATION_NEAREST_NEIGHBOR Sharp blocks when enlarged; useful for pixel art
VALUE_INTERPOLATION_BILINEAR Smoother transitions; a useful starting point for general images
VALUE_INTERPOLATION_BICUBIC Uses a larger neighborhood; can produce smoother detail but may cost more work

Set these values with RenderingHints.KEY_INTERPOLATION. They are rendering hints; results can vary with the graphics implementation and destination. Shape antialiasing and image interpolation are separate settings. Enabling antialiasing alone does not select the image scaling algorithm.

Complete Java example

Save this file as ScaleImageExample.java.

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ScaleImageExample {
    private static final String[] NAMES = {"Nearest neighbor", "Bilinear", "Bicubic"};
    private static final Object[] HINTS = {
            RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR,
            RenderingHints.VALUE_INTERPOLATION_BILINEAR,
            RenderingHints.VALUE_INTERPOLATION_BICUBIC
    };

    public static void main(String[] args) throws Exception {
        BufferedImage image = createImage();
        if (args.length == 1 && args[0].equals("--export")) {
            SwingUtilities.invokeAndWait(() -> {
                try {
                    exportPanels(image);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            return;
        }
        if (GraphicsEnvironment.isHeadless()) {
            System.out.println("No display available. Run with --export instead.");
            return;
        }
        SwingUtilities.invokeLater(() -> showWindow(image));
    }

    private static BufferedImage createImage() {
        BufferedImage image = new BufferedImage(160, 100, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        try {
            g.setColor(new Color(33, 99, 200));
            g.fillRect(8, 8, 144, 84);
            g.setColor(Color.ORANGE);
            g.fillOval(20, 20, 50, 50);
            g.setColor(Color.WHITE);
            g.drawLine(0, 99, 159, 0);
            g.drawString("Java", 90, 60);
        } finally {
            g.dispose();
        }
        return image;
    }

    private static void showWindow(BufferedImage image) {
        JPanel content = new JPanel(new GridLayout(1, 3, 8, 8));
        for (int i = 0; i < HINTS.length; i++) {
            content.add(new ImagePanel(image, NAMES[i], HINTS[i]));
        }
        JFrame frame = new JFrame("Java image scaling");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static void exportPanels(BufferedImage image) throws IOException {
        for (int i = 0; i < HINTS.length; i++) {
            ImagePanel panel = new ImagePanel(image, NAMES[i], HINTS[i]);
            panel.setSize(320, 260);
            BufferedImage output = new BufferedImage(320, 260, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = output.createGraphics();
            try {
                panel.paint(g);
            } finally {
                g.dispose();
            }
            File file = new File("scaled-" + i + ".png");
            if (!ImageIO.write(output, "png", file)) {
                throw new IOException("No PNG writer available");
            }
            System.out.println("Saved " + file.getName() + " (320 x 260)");
        }
    }

    private static class ImagePanel extends JPanel {
        private final BufferedImage image;
        private final Object interpolation;

        ImagePanel(BufferedImage image, String title, Object interpolation) {
            this.image = image;
            this.interpolation = interpolation;
            setOpaque(true);
            setBackground(new Color(235, 235, 235));
            setBorder(BorderFactory.createTitledBorder(title));
            setPreferredSize(new Dimension(320, 260));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Insets insets = getInsets();
            int availableWidth = getWidth() - insets.left - insets.right;
            int availableHeight = getHeight() - insets.top - insets.bottom;
            if (availableWidth <= 0 || availableHeight <= 0) {
                return;
            }
            double scale = Math.min(
                    (double) availableWidth / image.getWidth(),
                    (double) availableHeight / image.getHeight());
            int width = Math.max(1, (int) Math.round(image.getWidth() * scale));
            int height = Math.max(1, (int) Math.round(image.getHeight() * scale));
            int x = insets.left + (availableWidth - width) / 2;
            int y = insets.top + (availableHeight - height) / 2;

            Graphics2D copy = (Graphics2D) g.create();
            try {
                copy.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation);
                copy.drawImage(image, x, y, width, height, this);
            } finally {
                copy.dispose();
            }
        }
    }
}

Run the program

Compile and launch on a desktop:

javac --release 25 ScaleImageExample.java
java ScaleImageExample

Scale Image Example

A window titled Java image scaling should contain three labeled panels. Each shows a blue rectangle, orange circle, diagonal line, and text. Resize the window horizontally and vertically. Each image should remain centered and retain its shape. The panel background shows through transparent parts of the source image.

You can also render the panels to PNG files without a display:

java -Djava.awt.headless=true ScaleImageExample --export

Expected console output:

Saved scaled-0.png (320 x 260)
Saved scaled-1.png (320 x 260)
Saved scaled-2.png (320 x 260)

The files are written to the working directory and replaced on later export runs. Open them side by side and zoom in on the diagonal line and circle. File 0 uses nearest neighbor, file 1 uses bilinear interpolation, and file 2 uses bicubic interpolation. Exact font appearance and border dimensions depend on the environment.

How the drawing works

The drawImage(image, x, y, width, height, observer) overload scales the source into the destination rectangle. The original BufferedImage stays 160 × 100 pixels. Display scaling does not resize its stored pixel grid or modify a file.

The panel subtracts its border insets before calculating the available area. This keeps the drawing inside the titled border. Transparent source pixels reveal the panel background, which super.paintComponent(g) paints first.

Passing this supplies the panel as an ImageObserver. A BufferedImage already has its pixel data, so this example does not need to wait for asynchronous image loading.

We create the source before scheduling the UI. Swing component construction and updates happen on the Event Dispatch Thread. The export mode uses that thread too. Its call to panel.paint(g) deliberately renders the complete component, including its border, into an offscreen image. In a normal interactive application, request screen painting with repaint() instead of calling paint() yourself.

For an external file, load it with ImageIO.read() before constructing the UI and check for a null result, as in Week 01. An interactive Open action should use a background worker for file I/O so the UI stays responsive.

This example scales from the original image on every paint. For large images, caching a scaled copy can help, but rebuild the cache when its target size or interpolation changes. Always scale from the original rather than repeatedly resizing a previously resized image. Strong downscaling may need more careful resampling than a single interpolation pass.

Try it yourself

Prevent enlargement by replacing the scale calculation with:

double scale = Math.min(1.0, Math.min(
        (double) availableWidth / image.getWidth(),
        (double) availableHeight / image.getHeight()));

Make the window larger. The image should stay at its original logical drawing size and remain centered. Make it smaller, and the image should shrink to fit. On a display with scaling enabled, logical drawing units do not necessarily correspond one-to-one with physical screen pixels.

Next, load a photograph and compare the interpolation methods when shrinking it. Which setting gives the most useful result for your image?

In the next post, we will use double buffering and animate an object with a Swing timer.

References