我创建了一个带有JPanel的窗体,里面有一些图形和一些按钮来控制事物。出于某种原因,我必须指定JPanel的宽度比要放入其中的实际图形小10px,并且低30px。什么导致这个问题?JPanel周围不需要的边框
这是代码:
public class Window {
public Sheepness sheepness;
public ButtonPanel buttonPanel;
public PaintPanel paintPanel;
public JFrame frame;
public Window(Sheepness sheepness) {
this.sheepness = sheepness;
frame = new JFrame("Sheepness simulation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setSize(width, height);
BorderLayout frameLayout = new BorderLayout();
JPanel background = new JPanel(frameLayout);
background.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttonPanel = new ButtonPanel(this);
background.add(BorderLayout.SOUTH, buttonPanel.buttonBox);
paintPanel = new PaintPanel(this);
paintPanel.setPreferredSize(new Dimension(320, 240));
background.add(BorderLayout.CENTER, paintPanel);
frame.getContentPane().add(background);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
public class PaintPanel extends JPanel {
public Window window;
public PaintPanel(Window window) {
this.window = window;
}
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.blue);
g.fillRect(0, 0, 320, 240);
}
}
截图为320×240一个首选大小:
Can't find source image http://www.cmbi.ru.nl/~estens/Sheepness/Sheepness_simulation_border.png。
您可以看到320 x 240 fillRect未完全填充JPanel,仍保留10 px宽度和30 px高度的边框。
截图与310 X 210使用preferredSize:
Can't find source image http://www.cmbi.ru.nl/~estens/Sheepness/Sheepness_simulation_noBorder.png。
现在它正好适合320 x 240 fillRect!
任何想法?
尝试添加'Border'('BorderFactory.createLineBorder(Color.RED,1)')围绕'paintPanel'这样就可以排除用'buttonPanel'相互作用。 – 2009-10-20 12:19:11
我用setPreferredSize:参数:宽度:640,高度:480,在setPreferredSize和setSize:Width:640,Height:480,frame.pack:Width:650,Height:510之后设置它后,检查了JPanel的大小。我想它与包装一切的算法有关。不过,尺寸增加并不奇怪吗?有没有办法告诉事情停止触摸我的组件的大小,只是他们的路线?我认为这应该是setPreferredSize,但我猜这不符合它的要求。 – FinalArt2005 2009-10-20 13:21:18
顺便说一句,添加边框显示与buttonPanel没有任何交互,因为它显示JPanel与按钮很好地排列在一起,但正如您可以从之前的注释中读取的那样,JPanel本身在打包后尺寸错误。 – FinalArt2005 2009-10-21 17:26:34