【发布时间】:2018-09-24 16:07:52
【问题描述】:
我仍然习惯于在 java 上绘制图形,并且正在尝试编写一个使用缓冲图像绘制背景的简单图形程序。然而,奇怪的是,即使我的 jpanel 大小设置为 1200x400,缓冲图像和 fillrect 方法也是如此,正如您在我所附的图片中看到的那样,存在一个小的“间隙”,因此面板明显大于 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();
}
}
【问题讨论】:
标签: java graphics jpanel paintcomponent graphics2d