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。谢谢!
答案 0 :(得分: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;
}
最后一项操作意味着如果hasBeenClicked
为false
,则会true
,如果是true
,则会false
。{{1}}如果您愿意,可以再次重复此操作。
答案 1 :(得分: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;
}
}
});
答案 2 :(得分:0)
如果你想要的只是你想要的,你也可以使用三元运算符:
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!");
}
答案 3 :(得分:0)
在班级中使用sentinel instance 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;
}
}
});