0

我正在尝试制作一个绘画程序,但我的画布有这个问题,每次我调整或最大化包含它的窗口时它都会清除。我真的不知道问题出在哪里,paint() 和 repaint() 方法在画布类中没有被覆盖,而且我没有使用任何 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();
}

}
4

1 回答 1

1

听起来像你画画,使用getGraphics- 答案是不要这样做。而是覆盖该paintComponent方法:

public class Canvas extends JPanel {

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

        /* do your drawings here */

    }

}

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

于 2013-04-07T22:38:43.000 回答