我尝试使用 Graphics 类画一条线,然后将其放入 JFrame 对象中:
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
class Window
{
private JFrame frame;
private Graphics g;
public void Window()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(15, 0);
frame.setSize(600, 200);
frame.setVisible(true);
}
public void DrawCross()
{
g.setColor(Color.BLACK);
g.drawLine(300,0, 200, 0);
frame.paint(g);
}
}
...
run:
Exception in thread "main" java.lang.NullPointerException
at Window.DrawCross(Window.java:33)
at Main.main(main.java:21)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
我在哪里错了,如何解决我的错误?无法初始化抽象的 Graphics 类对象。