import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseMotionEventDemo1 extends JFrame implements MouseListener,MouseMotionListener{
private static final long serialVersionUID = 1L;

int flag;//flag=1代表MouseMoved,flag=2代表MouseDragged
int x = 0;
int y = 0;
int startx,starty,endx,endy;//起始坐標與綹坐標

public MouseMotionEventDemo1(){
Container contentPane = getContentPane();
contentPane.addMouseListener(this);
contentPane.addMouseMotionListener(this);
//setSize(300,300);
setVisible(true);
contentPane.setBackground(Color.white);
addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
);
}
//由mousePressed(),mouseReleased()取得拖曳的開始與結束坐標
public void mousePressed(MouseEvent e){
startx = e.getX();
starty = e.getY();
}
public void mouseReleased(MouseEvent e){
endx = e.getX();
endy = e.getY();
}
public void mouseEntered(MouseEvent e){

}
public void mouseExited(MouseEvent e){

}
public void mouseClicked(MouseEvent e){

}
//mouseMoved(),mouseDragged()取得鼠標移動的每一個坐標,應調用repaint()方法
public void mouseMoved(MouseEvent e){
flag = 1;
x = e.getX();
y = e.getY();
repaint();
}
public void mouseDragged(MouseEvent e){
flag = 2;
x = e.getX();
y = e.getY();
repaint();
}
public void update(Graphics g){
//g.setColor(this.getBackground());
//g.setColor(Color.white);
//g.fillRect(0, 0, getWidth(), getHeight());
//g.setColor(Color.red);
paint(g);
}
public void paint(Graphics g){
g.setColor(Color.red);
if(flag==1){
g.drawString("鼠標坐標:("+ x+","+y+")",10,50);
g.drawLine(startx,starty,endx,endy);
}
if(flag==2){
g.drawString("拖曳鼠標坐標:("+x+","+y+")" ,10, 50);
g.drawLine(startx, starty, endx, endy);
}
}

public static void main(String[] args){
new MouseMotionEventDemo1();
}
}
大家运行下看看是什么现象?为什么在我的机子上会出现contenePane是透明的,而且“拖曳鼠標坐標:("+x+","+y+")"”这些字都很模糊,,是我的机子卡的缘故吗?大家运行一下吧。。看看有没有出现我这种现象?

解决方案 »

  1.   

    public void paint(Graphics g){
            //public Graphics2D createGraphics(){       // }
            g.setColor(Color.white);//**改变之处**
            g.fillRect(0, 0,getWidth(),getHeight());//**改变之处**
            g.setColor(Color.red);
            if(flag==1){
                g.drawString("鼠标坐标:(" + x + "," + y + ")",10,50);
                g.drawLine(startx,starty,endx,endy);
            }
            if(flag==2){
                g.drawString("拖曳鼠标坐标:("+x+","+y+")" ,10, 50);
                g.drawLine(startx, starty, endx, endy);
            }
        }
    每次重绘时,要先把画板擦干净。
      

  2.   

    哦。那你可以用下BufferedImage缓冲类。
    把图形先画在缓冲上,在又缓冲画到画板上。而画板每次画之前都更新一下。