Java如何设置JList组件的单元格宽度和高度?

JList可以通过设置fixedCellWidth和fixedCellHeight属性来定义a的单元格宽度和高度。这些属性有一个对应的方法,称为setFixedCellWidth(int width)和setFixedCellHeight(int height)。

package org.nhooo.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Vector;

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

    private void initialize() {
        // 初始化Windows默认关闭操作,大小和布局
        // 用于放置组件。
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(300, 150);
        setLayout(new BorderLayout(5, 5));

        // 创建要由JList组件使用的向量数据的列表。
        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);

        // 将操作侦听器添加到按钮以退出应用程序。
        JButton button = new JButton("CLOSE");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        // 添加滚动窗格,在该窗格中包装了JList组件,然后
        // 面板中央和南部的按钮
        getContentPane().add(pane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }

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