2009-09-18 173 views
1

我必須編寫一個小程序,在左側我必須使用一個面板來包含可以是按鈕列表的車輛列表,這是什麼問題,車輛的數量沒有給出! ! 所以,我需要滾動面板時車輛的數量實在是太多了,jscrollpane滾動面板

我的JFrame的做到這一點,但它並不能與面板的工作是正確的,請幫我用一個例子

我使用的代碼到滾動面板是:

public class VehicleList extends JPanel { 
    private ArrayList<VehicleReport> vehicles; 
    private ArrayList<JButton> v_buttons = new ArrayList<JButton>(); 



public void showList(ArrayList<Vehicles> vehicles) 
{ 
    this.vehicles = vehicles; 
    //... 
    add(getScrollpane()); 
    setSize(155,300); 

} 

public JScrollPane getScrollpane() 
{ 
    JPanel panel = new JPanel(); 
    panel.setPreferredSize(new DimensionUIResource(150, 300)); 
    GridBagLayout gridbag = new GridBagLayout(); 
    GridBagConstraints constraint = new GridBagConstraints(); 
    panel.setLayout(gridbag); 
    constraint.fill = GridBagConstraints.HORIZONTAL; 
    JLabel title = new JLabel("Vehiles list"); 
    constraint.gridwidth = 2; 
    constraint.gridx = 0; 
    constraint.gridy = 0; 
    constraint.ipady = 230; 
    gridbag.setConstraints(title, constraint); 
    panel.add(title); 
    // end of set title 
    constraint.gridwidth = 1; 
    int i=1; 

    for(JButton jb : v_buttons) 
    { 
     constraint.gridx =0; 
     constraint.gridy = i; 
     gridbag.setConstraints(jb, constraint); 
     panel.add(jb); 
     JLabel vehicle_lable = new JLabel("car" + i); 
     constraint.gridx = 1; 
     constraint.gridy = i; 
     gridbag.setConstraints(vehicle_lable, constraint); 
     panel.add(vehicle_lable); 
     i++; 
    } 
JScrollPane jsp = new JScrollPane(panel); 
return jsp; 

}

}

在jaframe添加JScrollPane中後的JFrame我放置此

pack();

setSize(250,250);

setLocation(100,300);

它的工作很清楚!!!!

+0

你可以提供你已經代碼? – akf 2009-09-18 17:26:50

+0

嗨,我現在把它,謝謝你的關注... – sirvan 2009-09-18 17:41:34

回答

2

您也不會向我們展示VehicleList JPanel的佈局管理器。如果你沒有設置它,它默認爲FlowLayout,不像JFrame(你提到過它可以工作),其內容窗格默認爲BorderLayout。因此,也許你只需要到相關的代碼更改:

//... 
add(getScrollpane()); 

//... 
setLayout(new BorderLayout()); 
add(getScrollpane(), BorderLayout.CENTER); 
+0

感謝一百萬......沒錯! – sirvan 2009-09-18 18:13:42

1

您需要設置在水平和垂直滾動政策:

public void setHorizontalScrollBarPolicy(int policy) 
public void setVerticalScrollBarPolicy(int policy) 

使用:

JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED 
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER 
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS 

和:

JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED 
JScrollPane.VERTICAL_SCROLLBAR_NEVER 
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS 

因此,例如:

jscrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 
+1

(VERTICAL | HORIZONTAL)_AS_NEEDED是默認值 – Nate 2009-09-18 18:24:46

+0

當我發佈答案時,沒有示例代碼,所以我想也許他不小心設置了值... – 2009-09-20 20:44:14