tags:

views:

827

answers:

1

When I run this code the selected item is not visible. I've already tried to run it in a separate thread with no luck.

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

Thanks for helping in advance!

+1  A: 

I figured it out!!

This is the code:

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

Instead of using the list that you passed into the createScrollPane() method, you create a new one.

jjnguy
:) Now I ask myself, why this error? Too many hours of hacking. Thanks!
Roman Glass
Ha, it took me a bit to find. Until I decided to carefully debug the code in Eclipse.
jjnguy