我仍然习惯在 java 上绘制图形,并尝试编写一个简单的图形程序,使用缓冲图像绘制背景。然而,奇怪的是,即使我的 jpanel 大小设置为 1200x400,缓冲图像和 fillrect 方法也设置为 1200x400,但正如您在我所附的图片中看到的那样,存在一个小“间隙”,因此面板明显大于 1200x400,但是我不明白为什么? setPreferredSize 方法实际上做了什么?此外,当我将 fillrect 方法和 bufferedimage 更改为 1300x500 时,不再有间隙,因此这显然是问题所在。如果有人对我哪里出错有任何建议,我将不胜感激,谢谢
这是我的代码:
public class Q2 extends JPanel {
private BufferedImage image;
public static void main(String[] args) {
Q2 test = new Q2();
}
public Q2() {
this.init();
}
private void init() {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setContentPane(this);
this.setPreferredSize(new Dimension(1200,400));
refreshCanvas();
window.pack();
window.setVisible(true);
window.setResizable(false);
}
public void paintComponent(Graphics g) {
Graphics2D twoD = (Graphics2D) g;
twoD.drawImage(image,0,0,null);
}
private void refreshCanvas() {
image = new BufferedImage(1200,400,BufferedImage.TYPE_INT_ARGB);
Graphics2D twoD = image.createGraphics();
twoD.setColor(Color.BLACK);
twoD.fillRect(0, 0, 1200,400);
repaint();
}
}
最佳答案
看看这个答案 here 。
您必须将window.setResizeable(false);
放在之前window.pack();
。这应该可以修复它。
关于Java 2D 图形 BufferedImage FillRect 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49831542/