【问题标题】:Java 2D Graphics BufferedImage FillRect issueJava 2D Graphics BufferedImage FillRect 问题
【发布时间】: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


    【解决方案1】:

    看看这个答案here

    你必须把window.setResizeable(false); 之前 window.pack();。这应该可以解决它。

    【讨论】:

    • 是的,这已解决,谢谢,没有意识到 setresizable 的位置会有所不同
    猜你喜欢
    • 2019-01-03
    • 1970-01-01
    • 2020-07-21
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 2012-04-03
    相关资源
    最近更新 更多