2014-11-04 68 views
0

我有一個Java的骰子程序,通過點擊一個「滾動」按鈕滾動5個骰子。限制JButton可以被點擊的次數?

我正在嘗試使按鈕被點擊3次後,它被禁用,除非關閉並重新打開,否則無法點擊。

謝謝!

topPanel.add(button1); 
int i = 0; 
button1.setToolTipText("Click this button to roll the dice."); 
button1.setForeground(Color.red); 
button1.setContentAreaFilled(false); 
button1.setFocusPainted(false); 
button1.setBorderPainted(false); 
if (i >= 3) { 
    button1.setEnabled(false); 
} else { 

    i++; 
} 
button1.setFont(new Font("Arial", Font.BOLD, 15)); 
button1.setPreferredSize(new Dimension(40, 25)); 
button1.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent event) { 
      die1.roll(); 
      die1.draw(dk); 
      die2.roll(); 
      die2.draw(dk); 
      die3.roll(); 
      die3.draw(dk); 
      die4.roll(); 
      die4.draw(dk); 
      die5.roll(); 
      die5.draw(dk); 
+0

使用一個變量,如果條件 – 2014-11-04 19:36:34

+0

我將如何做呢?我很難弄清楚我會在哪裏放置代碼以及它將包含什麼內容。 – 2014-11-04 19:38:35

回答

0

使用一個變量,並且如果條件 聲明變量以外

int i=0; 

按鈕執行的動作事件內

if(i>=3){ 
    button.setEnabled(false); 
}else{ 
    // do anything 
} 
i++; 

移動代碼事件

int i = 0; 

    topPanel.add(button1); 
    button1.setToolTipText("Click this button to roll the dice."); 
    button1.setForeground(Color.red); 
    button1.setContentAreaFilled(false); 
    button1.setFocusPainted(false); 
    button1.setBorderPainted(false); 

    button1.setFont(new Font("Arial", Font.BOLD, 15)); 
    button1.setPreferredSize(new Dimension(40, 25)); 
    button1.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent event) { 

if (i >= 3) { 
     button1.setEnabled(false); 
    } else { 

       die1.roll(); 
       die1.draw(dk); 
       die2.roll(); 
       die2.draw(dk); 
       die3.roll(); 
       die3.draw(dk); 
       die4.roll(); 
       die4.draw(dk); 
       die5.roll(); 
       die5.draw(dk); 
    } 
i++; 
} 
+0

我這樣做了,但按鈕仍然工作3次以上。 – 2014-11-04 19:47:19

+0

@JohnClark plz發佈你的代碼到發生了什麼 – 2014-11-04 19:48:05

+0

我已經編輯了部分代碼的帖子我使用了按鈕 – 2014-11-04 19:50:39

0

做一個計數器。每次點擊按鈕時,起始值爲零的變量都會增加。

0

您可以創建一個變量來計算該按鈕被按下的次數。 你創建你變量凡有int。

按鈕監聽器裏,你遞增1變量(或任何你想要的)

最後你把一個條件,當計數器到達你想要的號碼禁用按鈕。

0

以外利用初始化爲一個計數器零並在th的actionListener中增加e按鈕。每次單擊按鈕後,檢查計數器值是否小於您的預定限制。如果它達到按鈕對象的限制調用setEnabled(false)。

1

聲明一個變量在類的身體,

INT計數器= 0;

//在您的按鈕單擊事件

counter = counter + 1; 


if((counter > 0) && (counter < 3){ 

//你的程序邏輯來這裏

} 

if(counter >= 3){ 

button.setEnabled = false; 

Toast.makeText(activityname,"Restart the game", TOAST.LENGTH_LONG).show(); 

}