這是我的第一個Java GUI程序,真的只是我的第二個java程序,所以你要對我容易:)我的程序是很多谷歌上搜索和閱讀Java文檔的結果。我的問題是,我有一張52張精靈片,並試圖使用subImage將這些卡分別保存到緩衝圖像陣列中,僅用於測試目的,在窗口中顯示所有52個圖像。該文件是在我確信的那個正確的目錄中。我相信我的問題在於我使用Jlabels,或者僅僅是一個愚蠢的錯誤。不管怎麼說,這是我的類,它的精靈表拆分的JLabel將不顯示圖像 - NullPointerException異常
package gui;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class crdimgs extends JPanel {/**
*
*/
static final long serialVersionUID = 1L;
public final int width = 10;
public final int height = 20;
public int rows = 13;
public int cols = 5;
public BufferedImage image;
File cardimg = new File("Cards.jpg");
BufferedImage cards[];
public void loadsplit(File loadimage){
try{
image = ImageIO.read(loadimage);
} catch(Exception error){
System.out.print("error");
}
cards = new BufferedImage[cols*rows];
}
public crdimgs() {
loadsplit(cardimg);
setLayout(new GridLayout(rows, cols, 1, 1));
int x = 0;
int y = 0;
int subimg = 0;
for(int i = 0; i < rows; i++)
{
JPanel panel = new JPanel();
cards[subimg] = new BufferedImage(width, height, 5);
cards[subimg] = image.getSubimage(x, y, width, height);
panel.add(new JLabel(new ImageIcon(cards[subimg])));
add(panel);
x+=width;
subimg++;
}
y+=height;
x=0;
}
}
}
而我的主類
package gui;
import javax.swing.JFrame;
import java.awt.Color;
public class cards extends JFrame {
private static final long serialVersionUID = 1L;
public cards(){
setTitle("Poker");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1000, 700);
setLocationRelativeTo(null);
this.getContentPane().setBackground(Color.GREEN);
setVisible(true);
setResizable(false);
add(new crdimgs());
}
public static void main(String[] args){
new cards();
}
}
錯誤我收到的那一刻是:
errorException in thread "main" java.lang.NullPointerException
at gui.crdimgs.<init>(crdimgs.java:53)
at gui.cards.<init>(cards.java:22)
at gui.cards.main(cards.java:28)
注意在'Exception'第一線...'errorException線程 「main」 java.lang.NullPointerException'它以'error'開頭,它來自'ImageIO.read'語句。嘗試讀取文件時發生錯誤。繼氣墊船的建議 – MadProgrammer