设计一个面板,其中有一个面板ApartmentPanel是展示电梯在楼层的运行.
ApartmentPanel有两个子面板:floorPanel和upAndDownPanel.
想法是一竖排显示电梯状态的文本框和乘客选择的上下按钮,一竖排JLabel表示floor,其中每个floor对应一个upbutton,一个downbutton还有一个电梯现在所在楼层。
主要问题是设置button和panel的大小和位置好像没用。就算设置了setlayout(null),好像还是按照flowLayout
在布局
涉及界面的代码如下:
public ApartmentPanel() {
super();
EtchedBorder b1=new EtchedBorder();
this.setLayout(null);
//this.setSize(800, 800);好像在本身设置本身大小没有效果
this.setBorder(b1);
//floor panel
floorPanel = new JPanel();
EtchedBorder b2=new EtchedBorder();
this.add(floorPanel);
floorPanel.setBounds(55, 5, 200, 585);
floorPanel.setLayout(new GridLayout(DEFAULT_FLOOR_NUMBER,1,0,0));

//up and down panel
upAndDownPanel = new JPanel();
this.add(upAndDownPanel);
upAndDownPanel.setBounds(5, 5, 50, 640);
this.setLayout(null);//实践:layout(null)和gridlayout没有区别//this.setLayout(newGridLayout(1,3*DEFAULT_FLOOR_NUMBER,0,(DEFAULT_DOOR_HEIGHT -3*25)/3 ));

//添加按钮和floorLabel
for(int i=0 ; i<DEFAULT_FLOOR_NUMBER ;i++ ){
floor[i] = new JLabel();
floor[i].setBorder(b2);
floor[i].setSize(DEFAULT_FLOOR_WIDTH,DEFAULT_FLOOR_HEIGHT);
floor[i].setText("floor "+ (10-i));
floorPanel.add(floor[i]);

//add up and down JButton  
//add currentFloor text
upButton[i] = new  JButton();
//upButton[i].setBounds(225, 5 + i*DEFAULT_FLOOR_HEIGHT, 25, 25);

System.out.print(upButton[i].getX());
System.out.println(upButton[i].getY());
//在此处打印出来的坐标,如果setBounds之后就是设置的坐标,如果不设置就是0.为什么呢?
currentFloor[i] = new JTextField("9");
    //currentFloor[i].setBounds(225, 30 + i*DEFAULT_FLOOR_HEIGHT , 25, 25); 
downButton[i] = new  JButton();
    //downButton[i].setBounds(225, 55 + i*DEFAULT_FLOOR_HEIGHT, 25, 25);

upAndDownPanel.add(upButton[i]);
upAndDownPanel.add(currentFloor[i]);
upAndDownPanel.add(downButton[i]);
}

解决方案 »

  1.   

    floorPanel这些layout也要设置为null才行哦
      

  2.   

    在使用布局管理器后, 组件的位置与大小由布局管理器来控制, 你自己设置是没有用的.要使setBound和setSize起作用, 正如楼上所说, 布局管理器设置为null.
      

  3.   

    樓上正解    使用四個參數的setBound  也就不用使setSize了
      

  4.   

    upandDown panel 没有设置layout(null) ;
    setBounds 貌似在上一级面板里面才好设置这个.不过都已经解决了.
    多谢楼上了~~