简体   繁体   English

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

[英]repaint() method in java not working properly

am doing that program to paint the mouse location in a panel , the program works fine but after like 10 seconds it stops painting the points... any help? 我正在执行该程序以在面板上绘制鼠标位置,该程序可以正常工作,但在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();


  }
 }

You call repaint within the paint method, causing an infinite loop. 您在paint方法中调用repaint ,从而导致无限循环。 Swing Timers are preferred for running periodic updates on components. 对于在组件上运行定期更新,首选摆动计时器

For custom painting in Swing the method paintComponent rather than paint should be overridden not forgetting to call super.paintComponent . 对于Swing中的自定义绘画,应该重写paintComponent方法而不是paint方法,不要忘记调用super.paintComponent

public void paint(Graphics g) should be public void paintComponent(Graphics g) . public void paint(Graphics g)应该是public void paintComponent(Graphics g)

And you isn't supposed to call repaint() inside this method. 而且您不应该在此方法内调用repaint()。

You should add an mouse listener outside this method, too. 您也应该在此方法之外添加鼠标侦听器。

An adapted example from Java Tutorials 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) {
    }


    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM