import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.scene.layout.HBox; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.event.EventHandler; import javafx.event.ActionEvent; public class Kalkulator extends Application { // trenger tilgang til disse i KnappBehandler TextField tall1, tall2; // tallene TextField resultat; // svaret // indre klasse - handling som skal skje naar vi trykker paa knappene class KnappBehandler implements EventHandler { @Override public void handle(ActionEvent e) { Button trykket = (Button) e.getSource(); // knappen som ble trykket double tallInn1 = 0.0; double tallInn2 = 0.0; try { tallInn1 = Double.parseDouble(tall1.getText()); // leser inn tall tallInn2 = Double.parseDouble(tall2.getText()); // leser inn tall } catch (NumberFormatException eksept) { System.out.println("Ikke tall"); return; } String operasjon = trykket.getText(); // hva staar paa knappePane double svar = 0.0; switch (operasjon) { case "+": svar = tallInn1 + tallInn2; break; case "-": svar = tallInn1 - tallInn2; break; case "x": svar = tallInn1*tallInn2; break; case "/": svar = tallInn1/tallInn2; break; } resultat.setText(" " + svar); } } @Override public void start(Stage teater) { VBox kulisser = new VBox(); HBox tekstPane = new HBox(); tekstPane.setAlignment(Pos.CENTER); tall1 = new TextField("tall1"); tall2 = new TextField("tall2"); tekstPane.getChildren().addAll(tall1, tall2); HBox knappePane = new HBox(); knappePane.setAlignment(Pos.CENTER); Button plussKnapp = new Button("+"); Button minusKnapp = new Button("-"); Button gangeKnapp = new Button("x"); Button deleKnapp = new Button("/"); knappePane.getChildren().addAll(plussKnapp, minusKnapp, gangeKnapp, deleKnapp); KnappBehandler handling = new KnappBehandler(); plussKnapp.setOnAction(handling); minusKnapp.setOnAction(handling); gangeKnapp.setOnAction(handling); deleKnapp.setOnAction(handling); resultat = new TextField("resultat"); kulisser.getChildren().addAll(tekstPane, knappePane, resultat); teater.setTitle("Kalkulator"); teater.setScene(new Scene(kulisser, 200, 100)); teater.show(); } public static void main(String[] args) { Application.launch(args); } }