我正在创建一个带有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:
您可以看到320 x 240 fillRect未完全填充JPanel,宽度为10 px且高度保持30 px的边框.
屏幕截图的首选尺寸为310 x 210:
现在它完全适合320 x 240 fillRect!
有任何想法吗?