[英]Thread NullPointerException
嘿,每當我運行此錯誤輸出時。
Exception in thread "Thread-2" java.lang.NullPointerException
at GraphicsTest.render(GraphicsTest.java:50)
at GraphicsTest.run(GraphicsTest.java:58)
at java.lang.Thread.run(Unknown Source)
這是我無法弄清楚為什么它不起作用的代碼。 我在網上搜索過,似乎找不到任何答案。 我是新手,只想在屏幕上繪制圖像。 然后也許以后再嘗試創建一個bufferedImage數組,但這看起來還需要一段時間。 在此先感謝您的幫助:)
public class GraphicsTest extends JPanel implements Runnable{
public static BufferedImage image;
private boolean isRunning = false;
public void start() {
isRunning = true;
new Thread(this).start();
}
public static void main(String args[]) {
GraphicsTest I = new GraphicsTest();
JFrame window = new JFrame("Test Rendering");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setLocationRelativeTo(null);
window.setPreferredSize(new Dimension(600, 400));
window.pack();
window.setVisible(true);
I.start();
try {
image = ImageIO.read(new File("Grap/roby.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void render() {
Graphics g = getGraphics();
g.drawImage(image, 0, 0, null);
}
@Override
public void run() {
while(isRunning) {
render();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
只是想在屏幕上繪制圖像
嘗試使用類似...
GraphicsTest gt = new GraphicsTest();
try {
image = ImageIO.read(new File("Grap/roby.png"));
I.add(new JLabel(new ImageIcon(image));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JFrame window = new JFrame("Test Rendering");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(gt);
window.setLocationRelativeTo(null);
window.setPreferredSize(new Dimension(600, 400));
window.pack();
window.setVisible(true);
看看如何使用標簽了解更多詳細信息。
切勿使用getGraphics
嘗試進行自定義繪畫,這不是Swing中繪畫的工作方式。
如果您真的想了解繪畫的工作原理,請查看AWT中的繪畫和Swing和執行自定義繪畫以獲取更多詳細信息。
您可能希望通讀Java TM編程語言的代碼約定 ,這將使人們更容易閱讀您的代碼,並使您閱讀其他代碼更容易
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.