我要写一个applet,在左边我必须用一个面板来包含一个车辆列表,这个列表可以是一个按钮,有什么问题,车辆的编号都没有给出!所以,当车辆数量太多时,我需要滚动面板,
我为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);
而且它显然是有效的!
发布于 2009-09-18 17:54:41
您也没有向我们展示VehicleList JPanel的布局管理器。如果您没有设置它,它将默认为FlowLayout,这与JFrame不同(您提到的BorderLayout可以在其中工作),它的内容窗格默认为BorderLayout。因此,您可能只需要将相关代码从:
//...
add(getScrollpane());至
//...
setLayout(new BorderLayout());
add(getScrollpane(), BorderLayout.CENTER);发布于 2009-09-18 17:34:30
您需要设置水平和垂直滚动策略:
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);https://stackoverflow.com/questions/1445843
复制相似问题