java中的repaint()方法无法正常工作

时间:2013-03-22 15:12:09

标签: java paint repaint

我正在做该程序在面板中绘制鼠标位置,该程序工作正常,但在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();


  }
 }

2 个答案:

答案 0 :(得分:2)

您在repaint方法中调用paint,导致无限循环。对于在组件上运行定期更新,首选Swing Timers

对于Swing中的自定义绘制,应该覆盖方法paintComponent而不是paint,而不要忘记调用super.paintComponent

答案 1 :(得分:2)

public void paint(Graphics g)应为public void paintComponent(Graphics g)

你不应该在这个方法中调用repaint()。

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

来自Java Tutorials

的改编示例
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) {
    }


    }
}