使用所谓双缓冲技术(只是听说过的)绘图:
package gui.test05;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
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 DrawLine1 extends Frame {
private int orgX;
private int orgY;
private int endX;
private int endY;
private Image oimg = null;
private Graphics og = null;
public DrawLine1() {
initDisplay();
initData();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
orgX = e.getX();
orgY = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
endX = e.getX();
endY = e.getY();
//用内存Image对象绘制
og.setColor(Color.RED);
og.setFont(new Font(null, Font.ITALIC | Font.BOLD, 12));
og.drawString(orgX + "," + orgY, orgX, orgY);
og.drawString(endX + "," + endY, endX, endY);
og.drawLine(orgX, orgY, endX, endY);
//通过重绘来画图
repaint();
}
});
}
private void initDisplay() {
this.setSize(400, 400);
this.setTitle("DrawLine");
this.setVisible(true);
//因为用了Componet.createImage方法创建内存Image对象(双缓冲),
//当组件重画时,是将内存中的Image对象在组件上画出,所以设置不可重改大小
this.setResizable(false);
}
private void initData() {
Dimension d = this.getSize();
oimg = this.createImage(d.width, d.height);
og = oimg.getGraphics();
}
@Override
public void paint(Graphics g) {
g.drawImage(oimg, 0, 0, this);
}
public static void main(String[] args) {
new DrawLine1();
}
}