我将一个JList添加到JScrollPane里面,
如何才能做到不管JList里面有及行数据,显示的始终是最后一行就是如果显示不够,滚动条自动滚动到最后一行

解决方案 »

  1.   


    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;public class AutoScrollList extends JFrame
    {
        private JScrollPane jScrollPane = new JScrollPane();
        private DefaultListModel listModel = new DefaultListModel();
        private JList list = new JList(listModel);
        private JPanel textPane = new JPanel();
        private JTextField jTextField = new JTextField();
        private JButton appendButton = new JButton("append");    public AutoScrollList()
        {
            getContentPane().setLayout(new BorderLayout());        jScrollPane.getViewport().add(list, null);        appendButton.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    String text = jTextField.getText().trim();
                    if (text.length() != 0)
                    {
                        listModel.addElement(text);
                        //滚动封闭视口中的列表,使指定单元可见
                        list.ensureIndexIsVisible(listModel.getSize() - 1);
                    }
                }
            });        textPane.setLayout(new BorderLayout());        textPane.add(jTextField, BorderLayout.CENTER);
            textPane.add(appendButton, BorderLayout.EAST);        getContentPane().add(jScrollPane, BorderLayout.CENTER);
            getContentPane().add(textPane, BorderLayout.SOUTH);
        }    protected void processWindowEvent(WindowEvent e)
        {
            super.processWindowEvent(e);
            if (e.getID() == WindowEvent.WINDOW_CLOSING)
            {
                System.exit(0);
            }
        }    public static void main(String[] args)
        {
            AutoScrollList frame = new AutoScrollList();
            frame.setSize(800, 500);
            frame.setLocation(100, 100);
            frame.setVisible(true);
        }
    }