如何使用“ensureIndexVisible”进行Swing滚动?

时间:2008-09-17 17:20:16

标签: java swing

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

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

1 个答案:

答案 0 :(得分: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()方法的列表。