重回的时候为什么一片空白?
[code=Java][/code]
package com.drawmyline;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class DrawMyLine extends Frame {
/**
* @param args
*/
Image outImage = null;//定义内存中的 Image对象.
Graphics ig =null;
private int X1;
private int Y1;
private int X2;
private int Y2;
public static void main(String[] args) {
// TODO Auto-generated method stub
DrawMyLine dyl = new DrawMyLine();
}
public DrawMyLine(){
this.setSize(1000, 1000);
this.setVisible(true); //设置可见性.
Dimension d =getSize();
Image i = createImage(d.width, d.height);
ig =i.getGraphics(); //内存中的 Image.
addWindowListener(new WindowAdapter() { //设置正常关闭.
public void windowClosing(WindowEvent e){
e.getWindow().dispose();
}
});
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
X1 = e.getX();
Y1 = e.getY();
}
public void mouseReleased(MouseEvent e){ //鼠标按下时画线.
X2 = e.getX();
Y2 = e.getY();
Graphics g = getGraphics();
g.drawLine(X1, Y1, X2, Y2);
g.drawString(X1+","+Y1, X1, Y1);
g.drawString(X2+","+Y2, X2, Y2);
ig.drawLine(X1, Y1, X2, Y2);
ig.drawString(X1+","+Y1, X1, Y1);
ig.drawString(X2+","+Y2, X2, Y2);
}
});
}
public void paint(Graphics g){ //重写paint()方法.
if (outImage!=null) {
g.drawImage(outImage, 0, 0, this);
}
}
}
[解决办法]
错误一: AWT早就淘汰了,不要用,用Swing
错误二: outImage 从头到尾都是 null,你重写的 paint() 方法不工作
错误三: 你在 paint() 方法以外的地方进行了绘制,直接用了Frame的Graphics来绘制,系统重绘Frame的时候,你所有的绘制都丢了
错误四: 你在 EDT 以外的线程里初始化GUI控件
错误五: 即使你用了正确的线程,正确初始化了 outImage,用它正确记录了你所有的绘制,写对了paint()方法(顺便一说,重写paint()是不合适的,直接重写Frame的paint()是更不合适的,如前所述,应该用Swing,应该定义一个控件如JPanel,然后重写它的paintComponent()方法)…………即使你前面这些都做对了,——那也不对,因为窗口的大小可以被用户的拖拽改变,而你的 outImage 是固定大小
…………
这就是我为什么直接给你贴了正确的代码。