建议使用BufferedImage做一个双缓冲,改后如下:
import java.awt.*;
import java.awt.image.*;//新增
import java.awt.event.*;
import javax.swing.*;public class Painer extends JFrame{
private int xValue = -10,yValue = -10;
private BufferedImage bi;
public Painer()
{
super("a simple paint program");
bi=new BufferedImage(300,150,BufferedImage.TYPE_INT_RGB);//新增
final Graphics f=bi.getGraphics(); //新增,f是bi的填充类
getContentPane().add(new Label("drag mouse to draw"),BorderLayout.SOUTH);
addMouseMotionListener(
new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
xValue = e.getX();
yValue = e.getY();
f.fillOval(xValue,yValue,4,4); //画图
repaint();
}
}
);
setSize(300,150);
show();
}
public void paint(Graphics g)
{
g.drawImage(bi,0,0,300,150,this); //显示图像
} public static void main(String args[])
{
Painer p = new Painer();
p.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{System.exit(0);}
}
);
}
}
可以解决你说的问题
import java.awt.*;
import java.awt.image.*;//新增
import java.awt.event.*;
import javax.swing.*;public class Painer extends JFrame{
private int xValue = -10,yValue = -10;
private BufferedImage bi;
public Painer()
{
super("a simple paint program");
bi=new BufferedImage(300,150,BufferedImage.TYPE_INT_RGB);//新增
final Graphics f=bi.getGraphics(); //新增,f是bi的填充类
getContentPane().add(new Label("drag mouse to draw"),BorderLayout.SOUTH);
addMouseMotionListener(
new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
xValue = e.getX();
yValue = e.getY();
f.fillOval(xValue,yValue,4,4); //画图
repaint();
}
}
);
setSize(300,150);
show();
}
public void paint(Graphics g)
{
g.drawImage(bi,0,0,300,150,this); //显示图像
} public static void main(String args[])
{
Painer p = new Painer();
p.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{System.exit(0);}
}
);
}
}
可以解决你说的问题
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货