jscrollpane滚动面板

时间:2009-09-18 17:22:48

标签: java user-interface swing applet awt

我必须写一个小程序,在左侧我必须使用一个面板来包含一个可以是按钮列表的车辆列表,问题是什么,没有给出车辆的数量! 所以,当车辆数量太多时,我需要滚动面板,

我为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;

}

}

在将jscrollpane添加到jframe之后,在jaframe中

我放置了这个

包();

setSize(250,250);

setLocation(100,300);

它工作得很清楚!!!!

2 个答案:

答案 0 :(得分:2)

您也没有向我们展示VehicleList JPanel的布局管理器。如果你没有设置它,它默认为FlowLayout,不像JFrame(你提到它可以工作),其内容窗格默认为BorderLayout。所以,您可能只需要更改相关代码:

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

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

答案 1 :(得分: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);