我不明白我在做错了什么。我收到以下错误:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Student.paint(Student.java:19)
at School$ButtonHandler.actionPerformed(School.java:127)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
以下代码应该为用户使用文本字段输入的等级绘制矩形:
public class Student extends Person {
static Graphics g;
public static void paint(Graphics g, int gradelevel) {
if (gradelevel == 9) {
g.setColor(Color.green);
g.fillOval(100, 100, 50, 50);
} else if (gradelevel == 10) {
g.setColor(Color.cyan);
g.fillOval(200, 200, 100, 100);
} else if (gradelevel == 11) {
g.setColor(Color.red);
g.fillOval(200, 200, 100, 100);
} else if (gradelevel == 12) {
g.setColor(Color.blue);
g.fillOval(200, 200, 100, 100);
}
}
}
答案 0 :(得分:1)
你宣布了
static Graphics g;
且g
从未初始化。所以当你致电g.setColor(Color.green);
,NullPointerException
刚才意识到代码中有两个g。
public static void paint(Graphics g, int gradelevel)
因此,在调用paint方法时,您可能会传递未初始化的static Graphics g;
。
如需更准确的答案,请显示您如何调用paint
方法。
答案 1 :(得分:0)
对于图形应用程序,您需要extends
一个容器(例如JFrame
,JPanel
)而不是覆盖paintComponent(Graphics g)
方法。请看下面的代码示例。否则,声明一个未初始化的Graphics
类将抛出NPE
。
public class Student extends JPanel {
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.green);
g.fillOval(100, 100, 50, 50);
..............
}
}