我正在尝试制作一个绘画程序,而我的画布存在此问题,每次我调整其大小或最大化包含它的窗口时,它都会清除。我真的没有任何想法,问题出在哪里,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 */

    }

}


如果这样做没有帮助,请花一些时间并发布您的绘图代码。

10-02 00:20
查看更多