gpt4 book ai didi

java - 调整窗口大小时 Canvas 会被清除

转载 作者:行者123 更新时间:2023-12-01 14:41:53 25 4
gpt4 key购买 nike

我正在尝试制作一个绘画程序,但我的 Canvas 遇到了这个问题,每次我调整大小或最大化包含它的窗口时,它都会清除。我真的不知道问题出在哪里,paint()和repaint()方法在canvas类中没有被重写,并且我没有使用任何适配器来调整窗口大小。任何帮助将不胜感激。

代码如下:

public class Plansa extends Canvas{
Image image;
Pencil pencil;
public Plansa(){
this.setSize(800, 600);
this.setBackground(Color.white);
pencil = new Pencil(this);
addMouseListener(pencil);
addMouseMotionListener(pencil);
}
public Plansa(int width, int height){
this.setBounds(0, 0, width, height);
this.setBackground(Color.white);
pencil = new Pencil(this);
addMouseListener(pencil);
addMouseMotionListener(pencil);
}
public Plansa(Image imag) {
this.setBackground(Color.white);
this.setSize(imag.getWidth(this), imag.getHeight(this));
image = imag;
this.image = imag;
this.repaint();
pencil = new Pencil(this);
addMouseListener(pencil);
addMouseMotionListener(pencil);

}


public Dimension getPreferredSize() {
if(image==null)
return new Dimension( 800, 600 );
int w = image.getWidth( this );
int h = image.getHeight( this );
return new Dimension( w, h );
}

}



public class Fereastra extends JFrame{
private Plansa plansa;

public Fereastra () {
super( "***Painter***" ) ;
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - this.getWidth())/2);
int y = (int) ((dimension.getHeight() - this.getHeight())/2);
this.setLocation(0, 0);
this.setSize(dimension);
plansa = new Plansa(this.getWidth(), this.getHeight());

//...

setDefaultCloseOperation(EXIT_ON_CLOSE);

add (plansa, BorderLayout.CENTER ) ;
pack();
}

}

最佳答案

听起来就像您使用 getGraphics 进行绘图 - 答案是不要这样做。而是重写 paintComponent 方法:

public class Canvas extends JPanel {

public void paintComponent(Graphics g) {
super.paintComponent(g) // paints background

/* do your drawings here */

}

}

如果这没有帮助,请花点时间发布您的绘图代码。

关于java - 调整窗口大小时 Canvas 会被清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15868238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com