2016-02-19 45 views
0

JScrollPane當我給它一個JPanel時完美工作,然後將JScrollPane直接添加到JFrameframe.getContentPane.add()然而,當我將JScrollPane添加到JPanel,然後將JPanel添加到JFrame它不起作用。我需要使用第二種方法,因爲我要在JPanelJFrame內添加多個內容,並且需要保持其組織性。這是我的代碼。JScrollPane在JPanel中不起作用

import java.awt.*; 
import javax.swing.*; 

public class Main { 

    /** 
    * @param inpanel asks if the JScrollPane should 
    * be inside of a JPanel (so other things can also be added) 
    */ 
    public static void testScroll(boolean inpanel) { 
     JFrame f = new JFrame(); 
     f.setLayout(new BorderLayout()); 
     f.setResizable(true); 
     f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 

     JPanel panel = new JPanel(); 
     panel.setBorder(BorderFactory.createLineBorder(Color.red)); 
     //panel.setLayout(new BoxLayout(panel, 1)); 
     panel.setLayout(new GridLayout(0,1)); 
     for (int i = 0; i < 100; i++) { 
      JLabel l = new JLabel("hey"+i,SwingConstants.CENTER); 
      l.setBorder(BorderFactory.createLineBorder(Color.green)); 
      l.setPreferredSize(new Dimension(200,200)); 
      panel.add(l); 
     } 
     JScrollPane scrollPane = new JScrollPane(panel); 
     scrollPane.setBorder(BorderFactory.createLineBorder(Color.blue)); 

     //**********THIS DOES NOT WORK HOW I WANT IT TO************ 
     if(inpanel){ 
      JPanel holder = new JPanel(); 
      holder.add(scrollPane); 
      f.getContentPane().add(holder); 
     } 
     //************THIS DOES WORK HOW I WANT IT TO**************** 
     else{ 
      f.getContentPane().add(scrollPane); 
     } 
     f.pack(); 
     f.setSize(500, 500); 
     f.setExtendedState(JFrame.MAXIMIZED_BOTH); 

     f.setVisible(true); 

     JScrollBar bar = scrollPane.getVerticalScrollBar(); 
     bar.setValue(bar.getMaximum()); 
     bar.setUnitIncrement(50); 
    } 

    public static void main(String[] args) { 

     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       testScroll(false); //OR TRUE 
      } 
     }; 
     SwingUtilities.invokeLater(r); 

    } 

} 

在main方法,如果我通過假的,它就像我之前提到的,但是當我通過真實的它顯示了無需滾動條。

傳遞虛假

enter image description here

圖片時傳遞true時

圖片

enter image description here

我需要一種方法來添加JScrollPaneJPanel,仍然有它的工作。 在此先感謝!

回答

3

你的問題是持有人JPanel的佈局。默認情況下,它是FlowLayout,在需要時不會重新調整其子組件的大小。改爲將其設置爲BorderLayout,並在需要時調整您的滾動窗格大小。如果您需要更復雜的東西,請查看佈局管理器教程。

+0

非常感謝!它現在有效。 –

+0

你爲什麼要調用f.pack()和f.setSize()? – FredK

+0

我只是在測試一些東西,我不會同時使用兩者 –