2012-05-15 282 views
-3
//Pylons 
int xCoord[]; 
int yCoord[]; 
int numSquare; 
boolean firstPaint; 

public void init() { 
    //Images Call 
    pylon = getImage(getDocumentBase(), "image/pylon.png"); 
    numClicks = 0; 

    //pylons 
    xCoord = new int[100]; 
    yCoord = new int[100]; 
    numSquare = 0; 
} 

public void paint(Graphics g) { 
    if (numClicks == 0) { 
     drawUI(g); 
     //probeDraw(g,2); 
    } 

    if (numSquare == 1) { 
     for (int k = 0; k < numSquare; k++) { 
      g.drawImage(pylon, xCoord[k], yCoord[k], this); 
     } 
     Minerals -= 100; 
     popMax += 9; 
    } 
} 

public boolean mouseDown(Event e, int x, int y) { 
    if (numClicks == 10) {//Title screen   
     numClicks++; 
     repaint(); 
    } 

    if (numSquare == 0) { 
     xCoord[numSquare] = x; 
     yCoord[numSquare] = y; 
     numSquare++; 
     repaint(); 
    } 
    return true; 
} 

當我這樣做,而不是隻是使用100,它會把它放在像-300,它會添加popMax像36而不是10.有時它會做到正確和有時它不會真的很煩人For循環/ if語句java

+4

請您源更具可讀性,併爲我們展示的一個小例子,什麼循環你有問題。一些自包含的東西等等。如果它與圖像,鼠標等沒有關係,請將其忽略。就像所有的換行符一樣。 – Nanne

+0

這是一個Swing應用程序嗎? –

回答

8

你正在更新paint(...)中的類級變量,這是每次UI組件需要重繪時調用的方法。我並不感到驚訝,這很煩人。

您需要將處理點擊操作的邏輯拆分出paint方法 - 並使用paint方法渲染組件的CURRENT STATE。

編輯:另外您的意見,並且不知道你的應用程序的結構,我想你會需要像這樣:

private void handlePylonPlacement() 
{ 
    if(decrementMinerals(-100)) 
     addPopMax(9); 
} 

private boolean decrementMinerals(int amount) 
{ 
    if(MaxMinerals - amount >= 0) // prevent situation where you go into negative minerals 
    { 
     MaxMinerals -= amount; 
     return true; 
    } 
    else 
     return false; 
} 

private void addPopMax(int amount) 
{ 
    if(popMax + amount <= MAX_POPULATION) // restrict addition to pop-max to a sane upper bound 
     popMax += amount; 
} 

public boolean mouseDown(Event e, int x, int y) { 
    if (numClicks == 10) {//Title screen   
     numClicks++; 
     repaint(); 
    } 

    if (numSquare == 0) { 
     xCoord[numSquare] = x; 
     yCoord[numSquare] = y; 
     numSquare++; 
     handlePylonPlacement(); // call your new handler 
     repaint(); 
    } 
    return true; 
} 
+1

絕對!當paint()被調用時,你無法控制。這絕對是問題! –

+2

@JacoVanNiekerk哈哈,你的意思是_an_問題:-) –

+0

@TonyEnnis哈! – mcfinnigan