簡體   English   中英

調整窗口大小時畫布會清除

[英]Canvas clears when resizing window

我正在嘗試制作一個繪畫程序,而我的畫布存在此問題,每次我調整其大小或最大化包含它的窗口時,它都會清除。 我真的沒有任何想法,問題出在哪里,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 */

    }

}

如果這樣做沒有幫助,請花一些時間並發布您的繪圖代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM