但我花了幾個小時試圖運行此代碼,它只是沒有工作。首先它應該在我的屏幕上打印圖像。到目前爲止,它不想打印我的圖像,但它仍然會打印矩形和字符串。我已經嘗試了很多東西,我甚至不知道它是否加載圖像了。有誰知道我做錯了什麼?使用NetBeans林是否有幫助需要幫助顯示我的圖像使用油漆
public class Screen extends JPanel implements Runnable {
public Thread thread = new Thread(this);
private Image Cat;
public Screen(Frame frame) {
thread.start();
}
public void run(){
System.out.println("this is running");
loadPic();
repaint();
try{
Thread.sleep(1);
} catch(Exception e) {}
}
public void loadPic(){
Cat = new ImageIcon("catIcon1.png").getImage();
System.out.println("Image Loaded!");
repaint();
}
public void paint(Graphics g){
g.drawString("sup tho!", 250, 250);
g.fillRect(50,50,50,50);
System.out.println("this works?");
g.drawImage(Cat, 0, 0, null);
System.out.println("Cat should be drawn");
}
}
1)對代碼塊使用一致的邏輯縮進。代碼的縮進旨在幫助人們理解程序流程! 2)public void paint(Graphics g){'should be'@Override public void paintComponent(Graphics g){super.paintComponent(g);'3)在動畫中使用Swing定時器。 4)不要在每個循環中加載圖像。 - 就像旁邊一樣,如果你基於你找到的代碼,丟失這些代碼 - 這是廢話。 – 2013-04-18 03:24:32
使用標準的Java命名約定。變量名稱不應以大寫字符開頭。 「貓」應該是「貓」。 – camickr 2013-04-18 03:27:10
我將它更改爲@Override public paintComponent(Graphics g){super.paintComponent(g);和我沒有做任何動畫到目前爲止,所以我不需要使用Swing TImer,但我不認爲。我也做了它,所以它不會加載每一個循環的圖像,但它仍然不會顯示...爲什麼它會顯示rectangels和字符串,但不是我加載的圖像? – 2013-04-18 03:36:11