我正在创建一个带有 JPanel 的表单,用于一些图形和一些用于控制事物的按钮。出于某种原因,我必须将 JPanel 指定为比我想要放入其中的实际图形小 10 px 和高 30 px。是什么导致了这个问题?
这是代码:
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 x 240 的屏幕截图:
找不到源图片 http://www.cmbi.ru.nl/~estens/Sheepness/Sheepness_simulation_border.png。
您可以看到 320 x 240 fillRect 并没有完全填满 JPanel,还保留了 10 px 宽和 30 px 高的边框。
首选大小为 310 x 210 的屏幕截图:
找不到源图片 http://www.cmbi.ru.nl/~estens/Sheepness/Sheepness_simulation_noBorder.png。
现在它完全适合 320 x 240 fillRect!
有任何想法吗?