0
我正在创建一个简单的Java2D程序。它应该从另一个类中绘制矩形,但它不起作用。如果你们中的一个人可以花一些时间看看我哪里出错,我会很感激。这是我明天到期的最后一项任务。从另一个类别绘制矩形
下面是我对迄今为止的工作代码:
Block.java
public class Block extends JPanel {
public Graphics2D g;
protected int posX = 0;
protected int posY = 0;
protected int w = 100;
protected int h = 100;
public void draw() {
g.setColor(Color.GREEN);
g.fillRect(posX, posY, w, h);
}
}
这里是主类:
public class main {
private static final long serialVersionUID = 1L;
private Block[] pie = new Block[5];
Timer timer;
main() {
final JPanel screen = new JPanel() {
int x = 0;
int step = 10;
public void paintComponent(Graphics g) {
super.paintComponent(g);
pie[0].g = (Graphics2D) g;
pie[0].draw();
}
};
JFrame f = new JFrame("Test Lab");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setContentPane(screen);
f.pack();
f.setLocationByPlatform(true);
f.setResizable(false);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run(){
new main();
}
});
}
}
非常感谢。
那么问题是什么?应该发生什么,发生了什么? – MikeTheLiar
我不知道。控制台上显示几条消息: 线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException \t at main $ 1.paintComponent(main.java:54) \t at javax.swing.JComponent.paint(未知来源) 其中第54行是指
pie[0].g = (Graphics2D) g;
– Mdkusuma请参阅http://stackoverflow.com/a/17871842/635678寻求帮助。 main.java中的第54行是什么? –