Scroll JScrollPane to bottom

前端 未结 12 925
庸人自扰
庸人自扰 2020-11-30 02:18

I need to scroll a JScrollPane to the bottom. The JScrollPane contains a JPanel, which contains a number of JLabel\'s.

To scroll to the top, I just do:



        
12条回答
  •  一向
    一向 (楼主)
    2020-11-30 02:46

    // Scroll to bottom of a JScrollPane containing a list of Strings.
    
    JScrollPane      scrollPane;
    DefaultListModel listModel;
    JList            list;
    
    listModel = new DefaultListModel();
    
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    list.setLayoutOrientation(JList.VERTICAL);
    list.setVisibleRowCount(-1); // -1 = display max items in space available
    
    scrollPane = new JScrollPane(list);
    scrollPane.setPreferredSize(new Dimension(200, 50));
    
    // Append text entries onto the text scroll pane.
    listModel.addElement("text entry one");
    listModel.addElement("text entry two");
    listModel.addElement("text entry three");
    listModel.addElement("text entry four");
    
    // Get the index of the last entry appended onto the list, then
    // select it, and scroll to ensure it is visible in the vewiport.
    int lastNdx = listModel.getSize() - 1;
    list.setSelectedIndex(lastNdx);
    list.ensureIndexIsVisible(lastNdx);
    
    JPanel panel = new JPanel();
    panel.add(scrollPane);
    

提交回复
热议问题