2009-09-18 176 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