I have this calculator working, but I can\'t figure out how to get the value in the resultpane
to the first textbox when you click the \"finish\" button.
Give your ResultPane a new public method that allows you to extract the text from its JLabel, something like:
public String getResultText() {
return result.getText();
}
And then call it when you want to get the text of that field:
public class ToText1Action extends AbstractAction {
public ToText1Action() {
putValue(NAME, "Finish");
}
@Override
public void actionPerformed(ActionEvent e) {
String resultText = resultPane.getResultText();
double number = // extract number from resultText
firstNumberField.setText(number);
}
}
Better still, simply store the latest result value in a double variable that is an instance field of the class, say called lastResult
and set the firstNumberField with that.
Note that you should not have empty catch blocks.
Edit
For example:
public class CalculatorPane extends JPanel {
private final ResultPane resultPane;
private final JLabel firstNumberLabel = new JLabel("First Number:");
private final JLabel secondNumberLabel = new JLabel("Second Number:");
private final JTextField firstNumberField = new JTextField(5);
private final JTextField secondNumberField = new JTextField(5);
private double result = 0.0; // ****** declared here
// ***** etc..... *****
public class DivideAction extends AbstractAction {
public DivideAction() {
putValue(NAME, "/");
}
@Override
public void actionPerformed(ActionEvent e) {
try {
double num1 = Double.parseDouble(firstNumberField.getText());
double num2 = Double.parseDouble(secondNumberField.getText());
result = num1 / num2; // ****** note variable not declared
resultPane.setResult(result);
} catch (NumberFormatException exp) {
// show error message
// set text fields to "0"
}
}
}
public class ToText1Action extends AbstractAction {
public ToText1Action() {
super("Finish");
putValue(MNEMONIC_KEY, KeyEvent.VK_F);
}
@Override
public void actionPerformed(ActionEvent e) {
firstNumberField.setText(String.format("%.2f", result));
}
}