简体   繁体   English

JScrollPane在JList上不起作用

[英]JScrollPane not working on JList

code: 码:

list1items = new DefaultListModel();
list1items.addElement("-");
list1 = new JList(list1items);
list1.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
list1.setBounds(0,0, 100,100);
JScrollPane list1scr = new JScrollPane(list1);
list1scr.setPreferredSize(new Dimension(20, 20));
list1.setVisibleRowCount(8);
getContentPane().add (list1scr);

And no scroll-bar appears. 并且没有滚动条出现。 When there are too many items, they are hidden, I cant reach them. 当物品太多时,它们是隐藏的,我无法到达它们。 How to solve this? 如何解决呢?

getContentPane().add(list1scr);

To expand on Michael Ardan's answer, you were adding you JList to the panel instead of the JScrollPane. 为了扩展Michael Ardan的答案,您将JList而不是JScrollPane添加到面板中。 The JScrollPane must be added to the panel and the JList must be added to the ScrollPane for it to work. 必须将JScrollPane添加到面板,并且必须将JList添加到ScrollPane才能工作。 There's really no need to use setBounds or setPreferredSize - get rid of them. 确实不需要使用setBoundssetPreferredSize摆脱它们。 JList takes care of all that when you call the setVisibleRowCount method. 当您调用setVisibleRowCount方法时,JList会处理所有这些工作。 Here's an example of your ScrollPane working. 这是您的ScrollPane工作的示例。 If you still have problems, plug your own code into this example until it breaks. 如果仍然有问题,请将您自己的代码插入此示例,直到出现问题为止。 Then tell us what broke it. 然后告诉我们是什么让它破了。 If not, accept Michael's answer. 如果没有,请接受迈克尔的回答。

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

public class Temp extends JPanel{
    public Temp(){

        DefaultListModel list1items = new DefaultListModel();
        list1items.addElement("-");
        for(int i = 0; i < 200; i++)
            list1items.addElement("Item " + i);
        JList list1 = new JList(list1items);
        list1.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
        JScrollPane list1scr = new JScrollPane(list1);
        list1.setVisibleRowCount(8);
        add (list1scr);
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new Temp());
        frame.pack();
        frame.setVisible(true);
    }
}

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

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