此代码应根据按下的按钮递增或递减,但只有增量才有效。这是代码的一小部分,因为我不允许发布整个代码:
作者Haris Irshad:
Listener listenNow = new Listener();
decrement.addActionListener(listenNow);
increment.addActionListener(listenNow);
panel.add(decrement);
panel.add(increment);
panel.add(label);
frame.add(panel);
frame.pack();
}
public static void main(String[] args) {
new IncrementDecrement();
}
private class Listener implements ActionListener {
public void actionPerformed(ActionEvent anyEvent) {
if (anyEvent.getSource() == decrement) {
info = label.getText();
dec = Integer.parseInt(info);
dec = dec - 1;
info = Integer.toString(dec);
label.setText(info);
} else if (anyEvent.getSource() == increment) {
info = label.getText();
}
dec = Integer.parseInt(info);
dec = dec + 1;
info = Integer.toString(dec);
label.setText(info);
}
}
}
答案 0 :(得分:0)
花点时间看看你的逻辑......
// If decrement action...
if (anyEvent.getSource() == decrement) {
// Decrement value...
info = label.getText();
dec = Integer.parseInt(info);
dec = dec - 1;
info = Integer.toString(dec);
label.setText(info);
// If increment action...
} else if (anyEvent.getSource() == increment) {
// Get the text...???
info = label.getText();
}
// And then increment the value when all else is done...
dec = Integer.parseInt(info);
dec = dec + 1;
info = Integer.toString(dec);
label.setText(info);
所以基本上,当你尝试递减该值时,实际上会减少它,但会立即再次增加它...
尝试将最后一段代码移到else-if
语句中,例如......
if (anyEvent.getSource() == decrement) {
info = label.getText();
dec = Integer.parseInt(info);
dec = dec - 1;
info = Integer.toString(dec);
label.setText(info);
} else if (anyEvent.getSource() == increment) {
info = label.getText();
dec = Integer.parseInt(info);
dec = dec + 1;
info = Integer.toString(dec);
label.setText(info);
}
答案 1 :(得分:0)
尝试以下
public void actionPerformed(ActionEvent anyEvent) {
if (anyEvent.getSource() == decrement) {
info = label.getText();
dec = Integer.parseInt(info);
dec = dec - 1;
info = Integer.toString(dec);
label.setText(info);
} else if (anyEvent.getSource() == increment) {
info = label.getText();
dec = Integer.parseInt(info);
dec = dec + 1;
info = Integer.toString(dec);
label.setText(info);
}
// These are causing the issue. These should be part of else if (anyEvent.getSource() == increment) {
/*dec = Integer.parseInt(info);
dec = dec + 1;
info = Integer.toString(dec);
label.setText(info);*/
// Coz of above every time this method is called it will result in increment.
}