2012-04-07 176 views
0

我有一個我想要動態填充的列表,因此需要滾動條。我已經添加了一個滾動條列表。問題是,當我嘗試將列表添加到面板。滾動條在列表中變得可見,但即使列表的元素變得更大,它們也不工作。添加滾動條到JList,JList被添加到JPanel

JPanel p4=new JPanel(); 
Container c=getContentPane(); 
myList=new JList(model); 
myList.setVisibleRowCount(5); 
myList.setFixedCellWidth(200); 

p4.add(new JScrollPane(myList,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, 
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS)); 
c.add(p4); 
+0

應該按預期工作(請參閱@ Robin的SSCCE) - 您沒有顯示的代碼出現錯誤... – kleopatra 2012-04-07 08:48:52

回答

2

這裏工作得很好。我用SplitPaneDemo.java文件中查找該SSCCE

import javax.swing.JFrame; 
import javax.swing.JList; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 
import javax.swing.ListSelectionModel; 
import java.awt.BorderLayout; 

public class SplitPaneDemo extends JPanel { 
    private JList<String> list; 
    private String[] imageNames = { "Bird", "Cat", "Dog", "Rabbit", "Pig", "dukeWaveRed", 
     "kathyCosmo", "lainesTongue", "left", "middle", "right", "stickerface"}; 
    public SplitPaneDemo() { 
    setLayout(new BorderLayout()); 

    list = new JList<>(imageNames); 
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 
    list.setSelectedIndex(0); 

    add(new JScrollPane(list)); 
    } 

    /** 
    * Create the GUI and show it. For thread safety, 
    * this method should be invoked from the 
    * event-dispatching thread. 
    */ 
    private static void createAndShowGUI() { 

    //Create and set up the window. 
    JFrame frame = new JFrame("SplitPaneDemo"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    SplitPaneDemo splitPaneDemo = new SplitPaneDemo(); 
    frame.getContentPane().add(splitPaneDemo); 

    //Display the window. 
    frame.pack(); 
    frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
    //Schedule a job for the event-dispatching thread: 
    //creating and showing this application's GUI. 
    javax.swing.SwingUtilities.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
     createAndShowGUI(); 
     } 
    }); 
    } 
} 
0

類似的問題在這裏剝奪了所有不必要的東西:here

我不認爲答案是你的情況一樣,雖然。當你添加東西到列表中時,問題可能會發生;你可以試試:

myList.revalidate(); 

它改變後。

+0

**否** - 重新驗證是**從不需要**在模型更改後需要**到其通知合同) – kleopatra 2012-04-07 08:46:55