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.control.Button; import javafx.scene.control.TextField; import javafx.event.EventHandler; import javafx.event.ActionEvent; import javafx.geometry.Pos; public class Calculator extends Application { public TextField tall1= null; public TextField tall2 = null; Button knappAdd = null; Button knappSub = null; Button knappMul = null; Button knappDiv = null; public TextField svar = null; @Override public void start (Stage stage) { VBox rootPane = new VBox(); tall1 = new TextField("Tall 1"); tall2 = new TextField("Tall 2"); knappAdd = new Button("+"); knappSub = new Button("-"); knappMul = new Button("*"); knappDiv = new Button("/"); ButtonHandler handler = new ButtonHandler(); knappAdd.setOnAction(handler); knappSub.setOnAction(handler); knappMul.setOnAction(handler); knappDiv.setOnAction(handler); svar = new TextField("SVAR"); HBox hbox1 = new HBox(); hbox1.getChildren().addAll(tall1, tall2); HBox hbox2 = new HBox(); hbox2.getChildren().addAll(knappAdd, knappSub, knappMul, knappDiv); rootPane.getChildren().addAll(hbox1, hbox2, svar); Scene scene = new Scene(rootPane); stage.setWidth(300); stage.setHeight(300); stage.setScene(scene); stage.setTitle("Kalkulator"); stage.show(); } class ButtonHandler implements EventHandler{ @Override public void handle (ActionEvent e) { Button denne = (Button) e.getSource(); int svarTall = 0; if (denne == knappAdd){ int en = Integer.parseInt(tall1.getText()); int to = Integer.parseInt(tall2.getText()); svarTall = en + to; } else if (denne == knappSub){ int en = Integer.parseInt(tall1.getText()); int to = Integer.parseInt(tall2.getText()); svarTall = en - to; } else if (denne == knappMul){ int en = Integer.parseInt(tall1.getText()); int to = Integer.parseInt(tall2.getText()); svarTall = en * to; } else if (denne == knappDiv){ int en = Integer.parseInt(tall1.getText()); int to = Integer.parseInt(tall2.getText()); try { svarTall = en / to; } catch(Exception f){} } svar.setText(""+svarTall); } } }