gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:52:01 24 4
gpt4 key购买 nike

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


}
}

最佳答案

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) {
}


}
}

关于java - java中的repaint()方法无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15573749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com