2013-04-03 71 views
0

我有一個方法返回一個jpanel,其佈局類似於圖像輪播。我已經檢查過,直接應用這個代碼在單個JPanel上正常工作。但是同樣的佈局正在多個地方使用。因此,我想創建一個通用方法來設置此佈局,並返回jPanel。這是我寫的方法:將一個Jpanel的內容添加到另一個 - Java Swings

public static JPanel loadImages(String Location) throws IOException{ 
    JPanel ImagePanel = new JPanel(); 
     File directory = new File(Location); 
    ImageIcon image; 

    String[] imageFiles = directory.list(); 
    DefaultListModel model = new DefaultListModel(); 
    JLabel lab1=new JLabel(); 
     JCheckBox chkbox ; 
    ImagePanel.setLayout(new GridBagLayout()); 

    for (int ii=0; ii<imageFiles.length; ii++) { 
     GridBagConstraints constraint = new GridBagConstraints(); 
     image = new ImageIcon(imageFiles[ii]); 
      lab1 = new JLabel(image); 
     constraint.gridx = ii; 
     constraint.gridy =0; 
     ImagePanel.add(lab1,constraint); 
    } 
    for (int ii=0; ii<imageFiles.length; ii++) { 
     GridBagConstraints constraint1 = new GridBagConstraints();   
     constraint1.anchor = GridBagConstraints.SOUTH;   
     chkbox = new JCheckBox(imageFiles[ii]); 
     constraint1.gridx = ii; 
     constraint1.gridy =1; 

     ImagePanel.add(chkbox, constraint1); 
     } 
    return ImagePanel; 

    } 

我的想法是,在所有的地方,這是需要的地方,我將有一個JScrollPane已經在UI設置。我想調用這個方法返回這個JPanel,我想把它添加到滾動窗格中。

private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) { 
     jScrollPane3.add(loadImages("C://users//images")); 
     jScrollPane3.revalidate(); 
     jScrollPane3.repaint(); 
} 

但是沒有顯示。是否因爲佈局未設置?

+0

不jScrollPane3使用什麼樣的佈局? –

+0

我沒有設置佈局。所以我猜測默認的佈局.. – Nemo

回答

1

請勿在JScrollPane上使用添加。

嘗試:

jScrollPane3.setViewportView(loadImages("C://users//images")); 
+0

簡短的回答,這就是JScrollPanes如何工作。 請參閱[JavaDoc](http://docs.oracle.com/javase/6/docs/api/javax/swing/JScrollPane.html)和[如何使用滾動窗格](http://docs.oracle。 COM/JavaSE的/教程/ uiswing /組件/ scrollpane.html) – flight2039

相關問題