gpt4 book ai didi

java - 线程 "AWT-EventQueue-0"java.lang.NullPointerException 中出现异常 - Paint()

转载 作者:行者123 更新时间:2023-11-30 08:05:11 26 4
gpt4 key购买 nike

我正在测试另一个简单的画线程序。第一个问题是错误。

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GUI$2.paint(GUI.java:57)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintChildren(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)

这是第 57 行的代码 g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);

panel = new JPanel(){
Point pointStart = null;
Point pointEnd = null;
int x = 1;
{
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
pointStart = e.getPoint();
}
public void mouseReleased(MouseEvent e){
pointEnd = e.getPoint();
}
});
addMouseMotionListener(new MouseAdapter(){
public void mouseMoved(MouseEvent e){
pointEnd = e.getPoint();
}
public void mouseDragged(MouseEvent e){
pointEnd = e.getPoint();
repaint();
}
});
}
public void paint(Graphics g){
super.paint(g);
g.setColor(a);
g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
}
};

请问,如何保存已经画好的线?谢谢

最佳答案

尝试一下(请注意,这是 paintComponent() 方法,而不是 paint()):

public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(a);
if(pointStart!=null && pointEnd!=null){
g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
}
}

关于java - 线程 "AWT-EventQueue-0"java.lang.NullPointerException 中出现异常 - Paint(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31227322/

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