[英]repaint() method in java not working properly
我正在执行该程序以在面板上绘制鼠标位置,该程序可以正常工作,但在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();
}
}
您在paint
方法中调用repaint
,从而导致无限循环。 对于在组件上运行定期更新,首选摆动计时器 。
对于Swing中的自定义绘画,应该重写paintComponent
方法而不是paint
方法,不要忘记调用super.paintComponent
。
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) {
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.