2015-04-02 242 views
-1

我正在創建一個使用按鈕的遊戲。我想在選中它後禁用一個按鈕,以便在遊戲重新啓動之前它不能再次使用,但是我無法實現此功能。有人能讓我知道如何去做這件事嗎?Java啓用/禁用按鈕

public void actionPerformed(ActionEvent e) { 
         if (q==2) { 
         label2.setText("Correct!"); } 
         else { 
          label2.setText("Wrong!!"); 
        }} 
+1

能否請您創建一個[MCVE(http://stackoverflow.com/幫助/ MCVE)。這可以幫助正試圖幫助你的讀者。 – StackFlowed 2015-04-02 20:50:10

回答

0

你可以從ActionEventgetSource事件的來源。然後將其與setEnabled

下面是一個例子轉換爲正確的類型,並禁用它,假設你使用JButton

public void actionPerformed(ActionEvent e) { 
    if (q==2) { 
     label2.setText("Correct!"); 
    } else { 
     label2.setText("Wrong!!"); 
    } 

    if(e.getSource() instanceof JButton) { 
     ((JButton)e.getSource()).setEnabled(false); 
    } 
} 
+0

一旦選擇了正確的按鈕,您如何重新啓用按鈕? – user3490456 2015-04-02 21:13:05

+0

@ user3490456每個調用'setEnabled'。將它們全部存儲在數據結構中(這將是更簡單的方法),或者使用它們父級的getComponents方法。 – resueman 2015-04-02 22:02:19

+0

謝謝你的幫助:) – user3490456 2015-04-02 22:43:33

0

呼叫button.setEnabled(false)禁用它,並button.setEnabled(true)恢復它。

0

有什麼麻煩?我相信你已經看過JButton文檔(假設你正在使用JButtons)。使用此功能將允許您啓用/禁用按鈕。

JButton.setEnabled(boolean)