Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

Her er én av manger løsninger som virker omtrent som foreslått over (men bruker litt andre navn på variabler og metoder):

Code Block
languagejava
collapsetrue
package kalkulator;

import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;

public class KalkulatorController {
	private double memory = 0.0;
	private String valueText = null;
	private String operator = null;

	@FXML
	TextField valueTextField;

	@FXML
	void initialize() {
		updateValueField();
	}

	private void updateValueField() {
		if (valueText != null) {
			valueTextField.setText(valueText);
			validateValueTextField();
		} else {
			valueTextField.setText(String.valueOf(memory));
		}
	}

	private void validateValueTextField() {
		try {
			// prøv å konvertere teksten i tekstfeltet
			Double.valueOf(valueTextField.getText());
			valueTextField.setStyle(null);
		} catch (Exception e) {
			valueTextField.setStyle("-fx-border-color: red;");
		}
	}

	private void append2ValueText(String s) {
		if (valueText == null) {
			valueText = "";
		}
		valueText = valueText + s;
	}

	private void clearValueText() {
		valueText = null;
	}

	private void convertAndStoreValueText() {
		memory = Double.valueOf(valueText);
	}

	private void convertValueTextComputeAndStoreValue() {
		double value = Double.valueOf(valueText);
		switch (operator) {
		case "/": memory = memory / value; break;
		case "*": memory = memory * value; break;
		case "+": memory = memory + value; break;
		case "-": memory = memory - value; break;
		}
	}

	private void storeOperator(String op) {
		operator = op;
	}

	@FXML
	void handleDigitButton(ActionEvent event) {
		Button button = (Button) event.getSource();
		append2ValueText(button.getText());
		updateValueField();
	}

	@FXML
	void handleOperatorButton(ActionEvent event) {
		if (valueText != null) {
			if (operator != null) {
				convertValueTextComputeAndStoreValue();
			} else {
				convertAndStoreValueText();
			}
		}
		clearValueText();
		Button button = (Button) event.getSource();
		storeOperator(button.getText());
		updateValueField();
	}

	@FXML
	void handleDesimalPoint() {
		append2ValueText(".");
		updateValueField();
	}

	@FXML
	void handleComputeButton() {
		if (valueText != null && operator != null) {
			convertValueTextComputeAndStoreValue();
			clearValueText();
			storeOperator(null);
		}
		updateValueField();
	}
	// manuell redigering av valueTextField

	@FXML
	void handleValueTextFieldChange(StringProperty prop, String oldValue, String newValue) {
		if (valueText != null && (! newValue.equals(valueText))) {
			valueText = newValue;
			validateValueTextField();
		}
	}
}

...