2016-02-19 80 views
-1
public class Hexagon extends JPanel { 
    // Team that controls the hexagon 
    public int controller; // 0 neutral // 1 is team 1 // 2 is team 2 
    // Color of the hexagon 
    // /* All attributes of the board, used for size an boarder etc... */ Board board 
    // /* Determines where the hexagon sits on the game board */ int position 

public static void main(String args[]) 
{ 
    JFrame j = new JFrame(); 
    j.setSize(350, 250); 
    for(int i = 0; i < 121; i++) 
    { 
     Hexagon hex = new Hexagon(); 
     j.add(hex); 
    } 
    j.setVisible(true); 
} 

@Override 
public void paintComponent(Graphics shape) 
{ 
    super.paintComponent(shape); 

    Polygon hexagon = new Polygon(); 

    // x, y coordinate centers, r is radius from center 
    Double x, y; 
    // Define sides of polygon for hexagon 
    for(int i = 0; i < 6; i++) 
    { 
     x = 25 + 22 * Math.cos(i * 2 * Math.PI/6); 
     y = 25 + 22 * Math.sin(i * 2 * Math.PI/6); 
     hexagon.addPoint(x.intValue(), y.intValue()); 
    } 
    // Automatic translate 
    hexagon.translate(10, 10); 
    // How do I manually control translate? 
    shape.drawPolygon(hexagon); 
} 
} 

如何手動平移多邊形?我需要做它來創建一個遊戲板。到目前爲止,我只完成了多邊形的自動翻譯,這絕對是我不需要的。手動平移多邊形

+0

請勿在截圖中發佈代碼。將其作爲文本發佈。 – khelwood

+0

這個問題還不清楚。更具體一些。 –

+0

它怎麼可能更清楚?我正在嘗試翻譯多邊形,並且我已經評論了自動翻譯多邊形的位置,這不是我正在嘗試執行的操作。 –

回答

3

我的意思是像參數,以便它並不總是10

然後你需要爲你的類參數:

  1. 創建類像`setTranslation(INT一個方法X ,int y)並將x/y值保存爲實例變量。
  2. 在paintComponent()方法中引用這些實例變量
  3. 然後,當您創建Hexagon時,您可以手動設置翻譯。

喜歡的東西:

public void setTranslation(int translationX, int translationY) 
{ 
    this.translationX = translationX; 
    this.translationY = translationY; 
} 

... 

//hexagon.translate(10, 10); 
hexagon.translate(translateX, translateY); 

... 

Hexagon hex = new Hexagon(); 
hex.setTranslation(10, 10); 

或者,你可以通過平移值作爲參數傳遞給你的六角類的構造函數。重點是如果您希望每個Hexagon具有不同的翻譯,則需要在Hexagon類中具有自定義屬性。

+1

哇,我現在覺得很愚蠢,這很有道理。 –