2012-05-15 120 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