我正在使用swing使用BorderLayout管理器在JPanel中构建一个包含4个JPanel的GUI:
我的代码如下所示:
JPanel middle = new JPanel();
middle.setLayout(new BorderLayout());
middle.add(midLabels,BorderLayout.NORTH);
middle.add(pickupButtons,BorderLayout.WEST);
middle.add(simulation,BorderLayout.CENTER);
middle.add(dropButtons,BorderLayout.EAST);
模拟面板只是一个扩展的JPanel,它会覆盖paintComponent来绘制图像。问题是,模拟区域位于左侧而不是中间:
我真正想要的是:
编辑,这是一个示例,我是否需要使用不同的布局管理器才能正确定位空的JPanel?:
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame {
final static int MAXFLOORS = 8;
public Test() {
setLayout(new BorderLayout());
setTitle("Simulator");
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
JPanel simulation = new JPanel();
JPanel dropButtons = new JPanel();
JPanel pickupButtons = new JPanel();
pickupButtons.setLayout(new GridLayout(MAXFLOORS, 1));
dropButtons.setLayout(new GridLayout(MAXFLOORS, 1));
setLayout(new BorderLayout());
add(simulation,BorderLayout.CENTER);
add(dropButtons,BorderLayout.EAST);
add(pickupButtons,BorderLayout.WEST);
for (int i = MAXFLOORS; i != 0; i--) {
JButton pb = new JButton("F" + i);
dropButtons.add(pb);
JButton db = new JButton("F" + i);
dropButtons.add(db);
}
repaint();
}
public static void main(String[] args) {
new Test();
}
}
答案 0 :(得分:3)
看看你的代码:
for (int i = MAXFLOORS; i != 0; i--) {
final JButton pb = new JButton("F" + i);
dropButtons.add(pb);
final JButton db = new JButton("F" + i);
dropButtons.add(db);
}
您要添加dropButtons
两次,而不是pickupButtons
。