[英]evaluating button clicks java
我有以下代碼:
for (int i = 0; i < dynamicVariable; i++) {
String tmpString = myArray[i];
JToggleButton tButton = new JToggleButton(tmpString);
myJPanel.add(tButton);
tButton.addActionListener(this);
}
JButton go = new JButton("go");
myJPanel.add(submit);
我在其中創建x個按鈕並將它們添加到面板中。 現在,我需要做的是,當用戶選擇正確的按鈕並按下按鈕時。 我評估所有選定的按鈕。 如果它們沒問題,則輸出true
,否則輸出false
。 如果他們選擇除一個以外的所有正確答案,則應評估為false
。 我只是不知道如何評估在actionPerformed()
方法中選擇的每個按鈕。
將所有按鈕放入List
或數組中,然后在單擊“ go
按鈕時對其進行迭代
private List<JToggleButton> listOfButtons;
//...
listOfButtons = new ArrayList<>(dynamicVariable);
for (int i=0; i<dynamicVariable;i++){
String tmpString= myArray[i];
JToggleButton tButton = new JToggleButton (tmpString);
listOfButtons.add(tButton);
myJPanel.add(tButton);
tButton.addActionListener(this);
}
JButton go= new JButton("go");
myJPanel.add(submit);
//...
// ActionListener of go button
public void actionPerformed(ActionEvent evt) {
for (JToggleButton btn : listOfButtons) {
if (btn.isSelected()) {
// Evaluate the state, set some flags
// get funky tonight
}
}
// Evaluate the final state once you know what
// buttons are actually selected
}
您應該首先為每個按鈕映射正確的值,然后如果用戶單擊“ 轉到”按鈕,則遍歷按鈕,檢查每個按鈕是否已正確打開或關閉。
簡而言之:
這是代碼:
// Put all values into a map. If the mentioned fruit has the mentioned
// color, then the answer is correct.
private Map<JToggleButton, Boolean> correctAnswers = new HashMap<JToggleButton, Boolean>() {{
put(new JToggleButton("A strawberry is red"), true);
put(new JToggleButton("A banana is blue"), false);
put(new JToggleButton("A lemon is yellow"), true);
put(new JToggleButton("An orange is orange"), true);
}};
void init() {
for (JToggleButton button : map.keySet()) {
// button.setActionListener(this); // The toggle buttons themselves
// do not need to have a listener, do they? Only when the user clicks
// "go", then the buttons should be evaluated, right?
myJPanel.add(button);
}
JButton submitButton = new JButton("go");
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
boolean wrong = false; // It's all good now, until a wrong
// answer is found.
// Iterate over all entries of our map.
for (JToggleButton button : this.buttons.keySet()) {
// Check if the selection state of the toggle button is
// equal to whether the answer is yes or no.
if (button.isSelected() != this.buttons.get(button)) {
// A button is pressed while it should not be pressed
// OR vice versa. Let's mark that at least one button
// is incorrect.
wrong = true;
}
}
// We found at least one incorrect button.
if (wrong) {
// DO SOMETHING
}
}
});
myJPanel.add(submitButton);
}
我尚未測試此代碼,但它應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.