我正在做该程序在面板中绘制鼠标位置,该程序工作正常,但在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();
}
}
答案 0 :(得分:2)
您在repaint
方法中调用paint
,导致无限循环。对于在组件上运行定期更新,首选Swing Timers。
对于Swing中的自定义绘制,应该覆盖方法paintComponent
而不是paint
,而不要忘记调用super.paintComponent
。
答案 1 :(得分:2)
public void paint(Graphics g)
应为public void paintComponent(Graphics g)
。
你不应该在这个方法中调用repaint()。
您也应该在此方法之外添加鼠标侦听器。
的改编示例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) {
}
}
}