2016-04-21 163 views
0

因此對於我的項目,我必須使用JLabelImageIcon將圖形繪製到屏幕上。我已經做了一些研究,但我似乎無法讓它向窗口渲染任何東西。它應該呈現每個20個不同位置的鳥,但屏幕保持空白。這裏是類文件:JLabel在屏幕上不顯示圖像

import javax.swing.*; 
import java.awt.*; 
import java.io.*; 

class Graphics 
{ 
    public static final String SIMULATOR_NAME = "Flocking Simulator 2K16"; 
    public static final int MAXIMUM_WIDTH = 1280; 
    public static final int MAXIMUM_HEIGHT = 780; 

    static Canvas canvas = new Canvas(); 

    private JFrame frame = new JFrame(); 

    public Graphics() 
    { 
     JFrame frame = new JFrame(); 
     frame.setTitle(SIMULATOR_NAME); 
     frame.setSize(MAXIMUM_WIDTH, MAXIMUM_HEIGHT); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
     frame.add(canvas); 
    } 

    public void Clear() 
    { 
     canvas.clear(); 
    } 

    public void DrawBirds(Flock birds, String graphic) 
    { 
     for (int i = 0; i < birds.GetMaximumBirds(); i++) 
     { 
      System.out.printf("Bird#" + i + "\n"); 
      Bird b = birds.GetBird(i); 
      frame.add(BirdGraphic(b, graphic)); 
     } 
    } 

    public JLabel BirdGraphic(Bird bird, String graphic) 
    { 
     System.out.printf(System.getProperty("user.dir") + File.separator + graphic + "\n"); 
     ImageIcon birdImage = new ImageIcon(System.getProperty("user.dir") + File.separator + graphic); 
     JLabel birdLabel = new JLabel(birdImage); 
     CartesianCoordinate loc = bird.GetPosition(); 
     birdLabel.setLocation((int)Math.floor(loc.getX() + 0.5), (int)Math.floor(loc.getY() + 0.5)); 
     return birdLabel; 
    } 
} 
+0

檢查'new File(System.getProperty(「user.dir」)+ File.separator + graphic).exists()'返回'true'。 – Berger

+0

剛剛檢查過它返回'true' – dave

+0

框架如何調用?除了'frame.add(canvas);'我沒有看到任何東西被添加到它。另請提供啓動您的應用程序的主要方法。 – Berger

回答

0

您不能直接在框架中添加標籤。您必須將它們添加到必須在框架中的某個面板。我們也不知道你真的想做什麼,你的Canvas的目的是什麼? 也不要混用awt和swing,我的意思是不要用Canvas,比較喜歡JComponent

+0

感謝您的迴應!我現在嘗試自己做這件事,但似乎無法讓它工作,請注意舉例說明如何將標籤添加到面板,然後將其轉換到框架上?我很抱歉在這一點上迷失了方向。 – dave

+0

您沒有給我們足夠的信息:您希望您的標籤出現在哪裏?你的畫布是什麼?更多代碼... –