2015-02-11 65 views
0

我試圖在可滾動的JPanel上使用十六進制圖像(720x835 GIF)製作六角板。我已經覆蓋了paintComponent方法在不同的特定位置繪製切片,並使用計時器在每個刻度處調用重繪。爲什麼我的圖像不能在JPanel上畫圖?

repaint()被調用時,doDrawing被調用。當調用doDrawing時,調用choseTile來繪製drawImage的圖塊。

出於某種原因,瓷磚沒有被繪製,我留下了一個空的黑色面板。爲什麼我的圖像不被繪製?是否因爲圖像太大?面板太大?

public class MapPanel extends JPanel { 

// Images for the tiles 
Image tile1; 
Image tile2; 
//etc 

// measurements for the tiles 
int tileX = 720; 
int tileY = 835; 
int dimensionX = 14760; 
int dimensionY = 14613; 

//Use this to keep track of which tiles goes where on a 20x20 board 
public int[][] hexer; 

/** 
* Create the panel. 
*/ 
public MapPanel(int[][] hexMap) { 

    hexer = hexMap; 
    setPreferredSize(new Dimension(dimensionX, dimensionY)); 
    setBackground(Color.black); 
    setFocusable(true); 
    loadImages(); 

    Timer timer = new Timer(140, animatorTask); 
    timer.start(); 
} 

//getting the images for the tiles 
private void loadImages() { 
    // Setting the images for the tiles 
    ImageIcon iid1 = new ImageIcon("/Images/tiles/tile1.gif"); 
    tile1 = iid1.getImage(); 
    ImageIcon iid2 = new ImageIcon("/Images/tiles/tile2.gif"); 
    tile2 = iid2.getImage(); 
    //etc 
} 

// Drawing tiles 
private void choseTile(Graphics g, int x, int y, int id) { 
    switch (id) { 
    case 1: 
     g.drawImage(tile1, x, y, this); 
     break; 
    case 2: 
     g.drawImage(tile2, x, y, this); 
     break; 
    //etc 

    } 
} 

// repainting stuff 
@Override 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); 

    doDrawing(g); 
} 

private void doDrawing(Graphics g) { 
    int actualX; 
    int actualY; 

    //set the painting coordinates and image ID then call the method to draw 
    for (int x = 0; x < 20; x++) { 
     for (int y = 0; y < 20; y++) { 
      if ((y + 1) % 2 == 0) { 
       actualX = x * tileX + 720; 
      } else { 
       actualX = x * tileX + 360; 
      } 
      if((x + 1) % 2 == 0){ 
       actualY = (y/2) * 1253 + 418; 
      }else{ 
       actualY = (y+1)/2 * 1253 + 1044; 
      } 
      if(hexer[x][y] != 0) 
      choseTile(g, actualX, actualY, hexer[x][y]); 
     } 
    } 
} 

private ActionListener animatorTask = new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     repaint(); 
    } 
    }; 
} 

編輯:我已經檢查,以確保圖像不null

+0

如果打印(X,Y)點(在幀圖像的左上角),您正在生成,他們開始在(360,1044)和結束(10800,13574),似乎值太大一個窗口。你確定你是以正確的方式計算它們嗎? – rafalopez79 2015-02-11 20:57:41

+0

把g.drawImage(...)放到paintComponent(Graphics g)中怎麼辦? – crAlexander 2015-02-11 21:22:45

+2

1)應用程序資源在部署時將成爲嵌入式資源,所以現在開始訪問它們是明智的做法。 [tag:embedded-resource]必須通過URL而不是文件訪問。請參閱[信息。頁面爲嵌入式資源](http://stackoverflow.com/tags/embedded-resource/info)如何形成的URL。 2)使用'ImageIO'加載它,它提供了很好的反饋。 – 2015-02-11 21:37:26

回答

1

按照Andrew Thompson的建議;我用ImageIO。由於ImageIO引發的錯誤,我能夠弄清楚我訪問圖像文件的方式是錯誤的。

+0

*「我能夠發現,由於ImageIO引發的錯誤,我訪問圖像文件的方式出錯了。」*'ImageIO'再次解救。 :) 很高興你把事情解決了。 – 2015-02-12 00:39:36

相關問題