2015-06-27 68 views
-1
buttonOne = new JButton("Who are you?"); 
    buttonOne.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      nameField.setText("Taha Sabra"); 
      ageField.setText("24 years old"); 
      buttonOne.setText("Clear Me!"); 
     } 
    }); 

這是我第一次點擊它時發生的情況。現在,一旦按鈕顯示Clear Me!,我希望能夠再次單擊它並清除nameField和ageField。謝謝!如何在Java中再次單擊按鈕時執行第二個操作?

+0

使用button.setActionCommand和getActionCommand做的工作 – Madhan

+0

或檢查button.text使用的ActionListener外的布爾因爲從內部類訪問的變量將無法正常工作之前和之後 – Madhan

回答

1

保持一個狀態變量(類字段),指示是否按鈕已經被點擊:

private boolean hasBeenClicked = false; 

然後改變你的actionPerformed的邏輯:

public void actionPerformed(ActionEvent arg0) { 
     if (! hasBeenClicked) { 
      nameField.setText("Taha Sabra"); 
      ageField.setText("24 years old"); 
      buttonOne.setText("Clear Me!"); 
     } else { 
      // Clear the fields 
      nameField.setText(""); 
      ageField.setText(""); 

      // Set the the text on the button to the original. 
      buttonOne.setText("Who are you?"); 
     } 
     hasBeenClicked = ! hasBeenClicked; 
    } 

這最後的操作手段如果hasBeenClickedfalse,它將變成true,如果它是true它將變成false。所以如果你願意,你可以重複一遍。

0

你可以使用你的ActionListener內一個簡單的布爾標誌:

buttonOne = new JButton("Who are you?"); 
buttonOne.addActionListener(new ActionListener() { 
    boolean clicked = false; 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     if (clicked) { 
      nameField.setText(""); 
      ageField.setText(""); 
      buttonOne.setText("Clear me again!"); 
     } else { 
      nameField.setText("Taha Sabra"); 
      ageField.setText("24 years old"); 
      buttonOne.setText("Clear Me!"); 
      clicked = true; 
     } 
    } 
}); 
0

如果這是你想要的OT實現,你也可以使用三元運算符:

public void actionPerformed(ActionEvent arg0) { 
    nameField.setText(nameField.getText().equals("") ? "Taha Sabra" : ""); 
    ageField.setText(ageField.getText().equals("") ? "24 years old" : ""); 
    buttonOne.setText(buttonOne.getText().equals("Clear Me!") ? "Who are you?" : "Clear Me!"); 
} 
0

使用sentinelinstance variable內你的班級在兩個動作之間切換。

boolean clicked = false; 

... 

buttonOne = new JButton("Who are you?"); 
buttonOne.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent arg0) { 
     if (!clicked) { 
      nameField.setText("Taha Sabra"); 
      ageField.setText("24 years old"); 
      buttonOne.setText("Clear Me!"); 
      clicked = true; 
     } else { 
      nameField.setText(""); 
      ageField.setText(""); 
      clicked = false; 
     } 
    } 
}); 
+0

必須' final'。 – Marv

+0

@Marv你是對的,這就是爲什麼我說使用類變量,如果更新答案,使這個更清晰 – GrahamA

+0

一個類變量?也許你的意思是一個領域? '靜態'是不需要的。 – Marv

相關問題