How do I set the cell width and height of a JList component?

The cell width and height of a JList can be defined by setting the fixedCellWidth and fixedCellHeight properties. These properties have a corresponding methods called setFixedCellWidth(int width) and setFixedCellHeight(int height).

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;

public class JListCellWidthAndHeight extends JFrame {
    public JListCellWidthAndHeight() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JListCellWidthAndHeight().setVisible(true));
    }

    private void initialize() {
        // Initialize windows default close operation, size and the layout
        // for laying the components.
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500, 175);
        setLayout(new BorderLayout(5, 5));

        // Create a list of vector data to be used by the JList component.
        Vector<String> v = new Vector<>();
        v.add("A");
        v.add("B");
        v.add("C");
        v.add("D");

        JList<String> list = new JList<>(v);
        list.setFixedCellWidth(50);
        list.setFixedCellHeight(50);

        JScrollPane pane = new JScrollPane(list);

        // Add an action listener to the button to exit the application.
        JButton button = new JButton("CLOSE");
        button.addActionListener(e -> System.exit(0));

        // Add the scroll pane where the JList component is wrapped and
        // the button to the center and south of the panel
        getContentPane().add(pane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }
}
JList Cell Width and Height Demo

JList Cell Width and Height Demo

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.