2015-11-03 64 views
1

所以我試圖寫一個基於瓦網格的遊戲,並提出了一個非常不尋常的解決方案。我用ImageIcon填充了一個帶有JLabels的2D JPanel數組。一切工作到目前爲止,但我沒有找到任何方式來積極渲染。 我嘗試了一些方法在互聯網上找到主動渲染,但他們沒有對我的想法起作用。你有一些想法如何實現這一點,而不重寫所有的畫布或類似的東西?使用ImageIcon瓷磚在JPanel上進行主動渲染? #Java

這裏是我的代碼:

窗口

public class Win extends JFrame { 
private static final long serialVersionUID = 1L; 
private BufferStrategy bs; 

public Win(int x, int y) { 

    this.setSize(x, y); 
    this.setVisible(true); 
    this.setResizable(false); 
    this.setIgnoreRepaint(true); 
    this.createBufferStrategy(2); 
    setBs(getBufferStrategy()); 
} 

public BufferStrategy getBs() { 
    return bs; 
} 

public void setBs(BufferStrategy bs) { 
    this.bs = bs; 
} 
} 

「畫」

public class Field extends JPanel { 
private static final long serialVersionUID = 5257799495742189076L; 

private int x = 0; 
private int y = 0; 
private JPanel backPanel[][] = new JPanel[19][19]; 
private BufferedImage images[] = new BufferedImage[100]; 
private JLabel image[][] = new JLabel[19][19]; 

public Field() { 

    this.setLayout(new GridLayout(20, 20)); 
    this.setIgnoreRepaint(true); 

} 

// Creates Panel Grid & Draws floor 
public void setPanels() { 
    for (int h = 0; h < 19; h++) { 
     for (int w = 0; w < 19; w++) { 

      backPanel[h][w] = new JPanel(); 
      backPanel[h][w].setLayout(new GridLayout(1, 1)); 

      image[h][w] = new JLabel(new ImageIcon(images[0])); 

      backPanel[h][w].add(image[h][w]); 

      this.add(backPanel[h][w]); 
     } 
    } 
} 

// Loads the Textures 
public void getTextures() throws IOException { 
    for (int i = 0; i < 1; i++) { 
     images[i] = ImageIO.read(new File("texture.png")); 

    } 
} 

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    g.drawImage(images[1], 0, 0, null); 

} 

public int getY() { 
    return y; 
} 

public void setY(int y) { 
    this.y = y; 
} 

public int getX() { 
    return x; 
} 

public void setX(int x) { 
    this.x = x; 
} 

} 

遊戲循環

public class GameLoop implements Runnable { 

private boolean runFlag = true; 

@Override 
public void run() { 
    Field field = new Field(); 
    Win window = new Win(640, 640); 
    window.add(field); 

    try { 
     field.getTextures(); 
    } catch (IOException e) { 

     e.printStackTrace(); 
    } 

    while (runFlag) { 

     try { 
      field.setPanels(); 
      window.getBs().show(); 
      Thread.sleep(20); 
     } catch (InterruptedException e) { 

      e.printStackTrace(); 
     } 

    } 

} 

public void stop() { 
    runFlag = false; 
} 

} 
+1

(搜索這裏)使用)現在阻斷了Thread.sleep(INT) – mKorbel

回答

2

一些替代方案:

  • 洗牌部件removeAll()add(),和validate()如圖here做。

  • 隨機播放內容並做setIcon(),如圖所示here

在任一情況下,

+0

重繪IST用的removeAll(現在的工作擺定時器,而不是可運行和驗證(),但其閃爍。在它上面工作。 Ty :) –