JScrollPane 中 JList 中的 DefaultListModel,看不到 JList

DefaultListModel in JList in JScrollPane, can't see the JList

我正在尝试使用 JScrollPane 中的 DefaultListModel 处理通用 JList。但是,我看不到 JList。

这是 class :

字段滚动列表:

    public class FieldScrollList<T> extends JScrollPane {

        private DefaultListModel<T> listModel;


        public int length () {
            return listModel.size();
        }

        public FieldScrollList () {

            setBorder(new TitledBorder(this.getClass().getSimpleName()));
            setBackground(Color.PINK);

            listModel = new DefaultListModel<>();
            JList<T> jList = new JList<>(listModel);
            add(jList);


            jList.setBorder(new TitledBorder(jList.getClass().getSimpleName()));


        }

        public void clear () {
            listModel.clear();
        }

        public void push(T t) {
            listModel.add(length(),t);
        }

        public <C extends Collection<T>> void pushAll(C coll) {
            coll.forEach(this::push);
        }

        public void pushAll(T[] coll) {
            for (T t : coll) {
                push(t);
            }
        }
    }

这里是 class 使用它。在此示例中,我将显示列表项的 FieldScrollList : hi and hello.

public class test {


    public static void main(String[] args) {
        new Thread(() -> {
            //---------------------------------- Content initialization ------------------

            JFrame frame = new JFrame("Test");
            JPanel panel = new JPanel();
            FieldScrollList<String> list = new FieldScrollList<String>();

            //---------------------------------- Strings initialization ------------------


            ArrayList<String> strings = new ArrayList<>();
            strings.add("Hello");
            strings.add("Hi");
            strings.forEach(list::push);

            //---------------------------------- JPanel configuration --------------------

            panel.setLayout(new GridLayout(1,1));
            panel.add(list);

            //---------------------------------- JFrame configuration --------------------

            frame.add(panel);
            frame.setPreferredSize(new Dimension(550,600));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            frame.setVisible(true);
        }).start();

    }
}

结果是这样的:

borders 和 setbackgrounds 的目的是(视觉上)显示内容的位置和区域

不明白为什么不显示字段

不要扩展 JScrollPane。您没有向滚动窗格添加任何功能。所有这些方法都与 ListModel 有关,与 JScrollPane.

无关
add(jList);

不要将组件添加到滚动窗格。 JScrollPane 是一个复合组件,包含 JScrollBars 和一个 JViewportJList 需要添加到视口中。

不要将 JList 添加到面板。您需要将 JScrollPane 添加到面板

通常这是使用如下基本代码完成的:

JScrollPane scrollPane = new JScrollPane( list );
panel.add( scrollPane );

您正在创建和操作不在 EDT 上的 Swing 对象。您的 Runnable 应该由 SwingUtilities.invokeLater 在 static void main.

中调用