0

正在执行该程序以在面板中绘制鼠标位置,该程序运行良好,但在 10 秒后它停止绘制点...有什么帮助吗?

   import java.awt.Color;
   import java.awt.Graphics;
   import javax.swing.JPanel;
   import javax.swing.JFrame;
    public class Draw extends JPanel {
public static  int newx;
public static  int newy;

   public void paint(Graphics g) {    

  Mouse mouse = new Mouse();
  mouse.start();

int newx = mouse.x;
int newy = mouse.y;
 g.setColor(Color.blue);  
   g.drawLine(newx, newy, newx, newy);
   repaint();




   }

   public static void main(String[] args) {

  JFrame frame = new JFrame("");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setBackground(Color.white);
  frame.setSize(2000,2000 );
  frame.setVisible(true);
  frame.getContentPane().add(new Draw());
  frame.revalidate();
  frame.getContentPane().repaint();


  }
 }
4

2 回答 2

2

您在方法repaint内调用paint,导致无限循环。Swing Timer更适合在组件上运行定期更新。

对于 Swing 中的自定义绘画,应该重写该方法paintComponent而不是忘记调用.paintsuper.paintComponent

于 2013-03-22T15:16:08.623 回答
2

public void paint(Graphics g)应该是public void paintComponent(Graphics g)

而且您不应该在此方法中调用 repaint() 。

您也应该在此方法之外添加一个鼠标侦听器。

改编自Java 教程的示例

public class MouseMotionEventDemo extends JPanel 
                                  implements MouseMotionListener {
    //...in initialization code:
        //Register for mouse events on blankArea and panel.
        blankArea.addMouseMotionListener(this);
        addMouseMotionListener(this);
        ...
    }

    public void mouseMoved(MouseEvent e) {
       Point point = e.getPoint();
       updatePanel(point); //create this method to call repaint() on JPanel.
    }

    public void mouseDragged(MouseEvent e) {
    }


    }
}
于 2013-03-22T15:16:22.580 回答