我正在尝试制作一个绘图程序,我的画布有这个问题,每次调整大小或最大化包含它的窗口时它都会清除。我真的没有想法问题,paint()和repaint()方法在canvas类中没有被覆盖,我没有使用任何addapter来调整窗口大小。任何帮助将不胜感激。
以下是代码:
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();
}
}
答案 0 :(得分:1)
听起来像你使用getGraphics
绘制 - 答案是不要做。而是覆盖paintComponent
方法:
public class Canvas extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g) // paints background
/* do your drawings here */
}
}
如果这没有帮助,请花点时间发布您的绘图代码。