1

当我运行此代码时,所选项目不可见。我已经尝试在没有运气的单独线程中运行它。

import javax.swing.JFrame;
import java.awt.Container;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.JScrollPane;
import java.awt.Dimension;

public class ScrollList extends JFrame {
    int defaultValue;

    ScrollList() {
        Container cp = getContentPane();
        JList list = createList();
        defaultValue = 20;

        cp.add(createScrollPane(list));
        pack();
        setVisible(true);
        list.ensureIndexIsVisible(defaultValue);
    }

    JList createList() {
        Integer[] model = new Integer[73];
        JList list = new JList(model);

        for (int i = 1; i < model.length; i++)
            model[i] = i;
        list.setSelectedIndex(defaultValue);

        return list;
    }

    JScrollPane createScrollPane(JList list) {
        JScrollPane s = new JScrollPane(createList());

        s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        s.setPreferredSize(new Dimension(100, 200));

        return s;
    }

    public static void main(String[] args) {
        new ScrollList();
    }
}
4

1 回答 1

1

我想到了!!

这是代码:

import javax.swing.JFrame;
import java.awt.Container;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.JScrollPane;
import java.awt.Dimension;

public class ScrollList extends JFrame {
    final int defaultValue = 20;

    ScrollList() {
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        Container cp = getContentPane();
        JList list = createList();

        cp.add(createScrollPane(list));
        pack();
        list.ensureIndexIsVisible(list.getSelectedIndex());

        setVisible(true);
    }

    JList createList() {
        Integer[] model = new Integer[73];
        JList list = new JList(model);

        for (int i = 1; i < model.length; i++)
            model[i] = i;
        list.setSelectedIndex(defaultValue);
        return list;
    }

    JScrollPane createScrollPane(JList list) {
        JScrollPane s = new JScrollPane(list); // MAJOR FIX HERE!
        s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        s.setPreferredSize(new Dimension(100, 200));
        return s;
    }

    public static void main(String[] args) {
        new ScrollList();
    }
}

您无需使用传递给 createScrollPane() 方法的列表,而是创建一个新列表。

于 2008-09-17T17:25:01.733 回答