import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class fff
{
public static void main(String []args)
{
new GExample().show();
}
}
 class GExample extends JFrame
{
public GExample()
{
this.setBackground(Color.white);
this.setTitle("图形示例");
this.setSize(300,200);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
setVisible(false);
System.exit(0);
}
}
  );
Container contentPane = getContentPane();
contentPane.add(new GExamplePanel());
contentPane.addMouseMotionListener(new GExamplePanel());
}

}

class GExamplePanel extends JPanel implements MouseMotionListener
{
int x,y;
public  void mouseMoved(MouseEvent ME)
{
x = ME.getX();
y = ME.getY();
}
public void paintComponent(Graphics g)
{
g.drawLine(x+10,y,x-10,y);
g.drawLine(x,y+10,x,-10);

}
public void mouseDragged(MouseEvent Me){}
}

解决方案 »

  1.   

    package com.greenteanet.csdn.mouse;import java.awt.Color;
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;import javax.swing.JFrame;
    import javax.swing.JPanel;public class MoustEvent {    /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            JFrame frame = new GExample();
            frame.setVisible(true);
        }}class GExample extends JFrame {    public GExample() {
    //        this.setBackground(Color.white);
            this.setTitle("图形示例");
            this.setSize(300, 300);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    setVisible(false);
                    System.exit(0);
                }
            });
            Container contentPane = getContentPane();
            contentPane.add(new GExamplePanel());
    //        contentPane.addMouseMotionListener(new GExamplePanel());
        }}class GExamplePanel extends JPanel implements MouseMotionListener {
        private int x, y;    public GExamplePanel() {
            addMouseMotionListener(this);
        }
        public void mouseMoved(MouseEvent ME) {
            x = ME.getX();
            y = ME.getY();
        }    public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawLine(x + 10, y, x - 10, y);
            g.drawLine(x, y + 10, x,  y -10);
            repaint();
        }    public void mouseDragged(MouseEvent ME) {    }
    }
      

  2.   

    修改的地方有paintComponent里面的repaint()语句,
    public GExamplePanel() {
            addMouseMotionListener(this);
        },
    //  contentPane.addMouseMotionListener(new GExamplePanel());
    以及private int x, y;