2015-10-05 82 views
-1

我正在製作一個繪製圖像的程序,看起來我犯了一個錯誤,我的程序只是不想繪製出圖像。有人能指出我的錯誤,因爲我真的沒有看到它。Java圖形PaintComponent問題。似乎無法找到該錯誤

package basic_game_programing; 

import java.awt.Graphics; 
import java.awt.Image; 


import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Practise extends JPanel { 

public Image image; 

     //#####PAINT__FUNCTION##### 
     public void PaintComponent(Graphics g){ 
      super.paintComponent(g); 

       ImageIcon character = new ImageIcon("C:/Documents and Settings/Josip/Desktop/game Šlije/CompletedBlueGuy.PNG"); 
       image = character.getImage(); 

       g.drawImage(image,20,20,null); 
       g.fillRect(20, 20, 100, 100); 
     } 



//######MAIN__FUCTION####### 
public static void main(String[]args){ 

    Practise panel = new Practise(); 


    //SETTING UP THE FRAME 
    JFrame frame = new JFrame(); 
    // 
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(500,500); 
    frame.add(panel); 


    //SETTING UP THE PANEL 

    // 









} 

}

+2

1的源代碼中的白色空間中的單個空行的全部就是* *永遠需要。 '{'之後或'}'之前的空行通常也是多餘的。 2.請參閱[檢測/修復代碼塊的懸掛緊密支架](http://meta.stackexchange.com/q/251795/155831),以解決我無法解決的問題。 –

回答

2

你使用的paintComponent代替miscapitalizing的paintComponent(注意第一個 「P」)。

  • 因此將PaintComponent更改爲paintComponent
  • 使用方法上方的@Override註釋讓編譯器告訴您何時犯這類錯誤。
  • 切勿將圖像讀入繪畫方法,因爲這會減慢需要快速的方法,並且在一次讀取就足夠時,可以反覆讀取圖像。
  • 該方法應該是protected而不是public
  • 使用ImageIO.read(...)來讀取圖像,並使用jar文件中的資源和相對路徑,而不是使用文件或ImageIcons。
  • 不要在JFrame上調用setVisible(true),直到之後添加所有組件,否則有些可能不會顯示。
  • 請閱讀教程,因爲大部分內容在這裏都有很好的解釋。

例如,

public class Practise extends JPanel { 

    private Image image; 

    public Practice() { 
     // read in your image here 
     image = ImageIO.read(.......); // fill in the ... 
    } 

    @Override // use override to have the compiler warn you of mistakes 
    protected void paintComponent(Graphics g){ 
     super.paintComponent(g); 

     // never read within a painting method 
     // ImageIcon character = new ImageIcon("C:/Documents and Settings/Josip/Desktop/game Šlije/CompletedBlueGuy.PNG"); 
     // image = character.getImage(); 

     g.drawImage(image, 20, 20, this); 
     g.fillRect(20, 20, 100, 100); 
    } 
} 
相關問題