繁体   English   中英

JScrollPane中JList中的DefaultListModel,看不到JList

[英]DefaultListModel in JList in JScrollPane, can't see the JList

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

这是课程:

FieldScrollList:

    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);
            }
        }
    }

这是使用它的类。 在此示例中,我创建了一个FieldScrollList,其中显示了列表项:hi和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();

    }
}

结果是这样的:

GUI创建

边框和setbackground的目标是显示内容的位置和区域(可视化)

我不明白为什么不显示字段

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

add(jList);

不要将组件添加到滚动窗格中。 JScrollPane是包含JScrollBarsJViewport的复合组件。 JList需要添加到视口中。

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

通常,这是通过基本代码完成的,例如:

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

您已创建并处理不在EDT上的Swing对象。 您的Runnable应该由static void main内部的SwingUtilities.invokeLater调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM