setVisibleRowCount不起作用

时间:2014-05-13 17:50:50

标签: java swing jscrollpane layout-manager jlist

    import java.sql.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import java.awt.*;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    public class Ui2 extends JFrame {
        JLabel l, l1;
        JFrame f;
        JPanel panel;
        JScrollPane scrollpane;
        int r;
        JList list;
        Ui2() {
            super("HADOOP GUI");
            panel = new JPanel();
            setContentPane(panel);
            panel.setSize(500, 500);
            SpringLayout x = new SpringLayout();
            panel.setLayout(x);
            DefaultListModel listmodel = new DefaultListModel();
            for (int i = 1; i <= 10; i++) {
                listmodel.addElement("Record" + i);
            }
            list = new JList(listmodel);

            list.setVisibleRowCount(5); // here is problem
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            scrollpane = new JScrollPane(list);
            x.putConstraint(SpringLayout.WEST, scrollpane, 150, SpringLayout.WEST, panel);
            x.putConstraint(SpringLayout.NORTH, scrollpane, 30, SpringLayout.NORTH, panel);
            panel.add(scrollpane);
            Dimension d = list.getPreferredSize();
            d.width = 200;
            scrollpane.setPreferredSize(d);
            l1 = new JLabel("Default");
            x.putConstraint(SpringLayout.WEST, l1, 150, SpringLayout.WEST, panel);
            x.putConstraint(SpringLayout.NORTH, l1, 300, SpringLayout.NORTH, panel);
            panel.add(l1);
            list.addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent arg0) {

                }

            });

        }
    }

1 个答案:

答案 0 :(得分:0)

似乎方法:setVisibleRowCount(int)不能用于添加到已设置Layoutmanager的JPanel的JLists。

我稍微重建了你的应用程序,因为我无法通过使用SpringLayout来实现它(我承认,我之前从未使用过它)。但是使用BorderLayout它工作正常。您只需将包含Scrollbar的{​​{1}}包装到您未定义Layoutmanager的外部JList中。我认为原因是Layoutmanager将根据可用空间布局组件,因此JPanel将被忽略!但请记住,使用另一个LayoutManager可能会显示不同的组件。我个人建议您使用setVisisbleRowCount进行简单的安排(北,南,......),BorderLayout用于一系列并行组件,FlowLayout用于高级安排。这应该足以满足几乎所有应用程序。

GridbagLayout