简体   繁体   中英

Display only 4 records and add a scroll bar to JList

I have added a JList, and made it to only display 4 records at a time. If there are more than 4 records the user should be able to scroll and view other records. But in my case, i get to see all 8-10 records that i added. The code is not showing the first 4 records and the scroll bar. Can someone tell me what i'm missing ?

import java.awt.BorderLayout;

public class FrameTest {

    private JPanel panel;
    private JFrame frame;
    private FrameTest ft;
    private JList list;

    public FrameTest() {
        initComponents();
        ft = this;
    }

    private void initComponents() {
        frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

        panel = new JPanel();
        panel.setBorder(new EmptyBorder(5, 5, 5, 5));
        panel.setLayout(new BorderLayout(0, 0));

        frame.getContentPane().add(panel);

        list = new JList();
        list.setVisibleRowCount(4);
        list.setModel(new AbstractListModel() {
            String[] values = new String[] {"adf", "gr", "rg", "g", "tg", "gt", "tg", "tg", "t", "gt", "gt"};
            public int getSize() {
                return values.length;
            }
            public Object getElementAt(int index) {
                return values[index];
            }
        });
        list.setSelectedIndex(1);
        panel.add(list, BorderLayout.SOUTH);

        frame.setLocationByPlatform(true);
        frame.pack();
        frame.setVisible(true);
    }


}

note: Above is a simplified version of my code.

Try adding the JList to JScrollPane and adding the scroll pane to you frame.

    panel.add(new JScrollPane(list), BorderLayout.SOUTH);

The visibleRowCount is used by getPreferredScrollableViewportSize to determine the number of rows that should be displayed in a scroll pane

setVisibleRowCount() changes the size preferences of the JList, but the actual size is determined by which Layout Manager is laying out the JList. Some layouts take notice of the preferred sizes, others don't.

The documentation says:

For a VERTICAL layout orientation, this sets or gets the preferred number of rows to display without requiring scrolling. For the HORIZONTAL_WRAP or VERTICAL_WRAP layout orientations, it defines how the cells wrap.

More details in the JavaDoc .

Use JScrollPane to achieve the scroll bar.

    JScrollPane scrollPane = new JScrollPane(list);
    panel.add(scrollPane, BorderLayout.SOUTH);

Details in the tutorial here: Using JScrollPane

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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