Trying to create action listeners to perform multiplication tasks. It seems to work, however it seems to ignore my last digit entered. I keep thinking I need a second variable to keep track of last command so that when the equal button is pressed it adds the current digit to the previous ones. But then I wouldn't I have to perform the task if the equal button is pressed?
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String numbers = e.getActionCommand();
if (begin) {
textField.setText(numbers);
begin = false;
}
else if (numbers.equals("C")) {
textField.setText("0.0");
action.reset();
}
else
textField.setText(textField.getText() + numbers);
}
}
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
String text = textField.getText();
if (begin) {
textField.setText("0.0");
action.setTotal("0.0");
}
else {
if (command.equals("+")) {
action.add(text);
begin = true;
}
else if (command.equals("=")) {
textField.setText(text);
System.out.println(action.getTotal());
}
textField.setText(action.getTotal());
}
}
}
Some explanation of variable. begin
simply checks if the current state of the JTextField
is blank or not. action
is simply the method to "add", it has other calls I want it to do.
Any suggestions on how to keep track of last command or get around so it doesn't ignore the last digit? These tasks are similar to those of a calculator.
EDIT: For those interested, here is what I ended up with.
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String numbers = e.getActionCommand();
// check if a number has been pressed
if (begin) {
textField.setText(numbers);
begin = false;
}
// if clear is checked
else if (numbers.equals("C")) {
action.reset();
begin = true;
operator = "=";
textField.setText("0.0");
}
// Once a number is pressed keep adding it to the text field until an operator is pressed
else
textField.setText(textField.getText() + numbers);
}
}
/**
* Action listener for Operators
*/
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// String command = e.getActionCommand();
// if nothing has been pressed
if (begin) {
textField.setText("0.0");
begin = false;
// else begin performing operation pressed
} else {
begin = true;
String text = textField.getText();
// right away add the value of the text field
if (operator.equals("=")) {
action.setTotal(text);
}
else if (operator.equals("+")) {
action.add(text);
}
// and so on for all the other operators.
textField.setText("" + action.getTotal());
// now capture the operator pressed.
operator = e.getActionCommand();
}
}
}