Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package calcwithlambda;
- /**
- *
- * @author Aamir khan
- */
- import java.util.Arrays;
- import java.util.function.BinaryOperator;
- import javafx.application.Application;
- import javafx.scene.Group;
- import javafx.scene.Scene;
- import javafx.scene.control.Button;
- import javafx.scene.control.ComboBox;
- import javafx.scene.control.Label;
- import javafx.scene.control.TextField;
- import javafx.scene.layout.HBox;
- import javafx.scene.paint.Color;
- import javafx.stage.Stage;
- import javafx.stage.StageStyle;
- public class Calculator extends Application {
- public static void main(String[] args) {
- launch(args);
- }
- @Override
- public void start(Stage stage) {
- stage.setTitle("A Simple Calculator");
- ComboBox<Operation> operations = new ComboBox<>();
- operations.getItems().addAll(Arrays.asList(Operation.values()));
- operations.setValue(Operation.values()[0]);
- TextField[] input = new TextField[2];
- for (int i = 0; i < input.length; i++) {
- input[i] = new TextField();
- input[i].setPromptText("Enter a number");
- }
- Label result = new Label("Click calculate for result");
- Button calculate = new Button("Calculate");
- calculate.setOnAction(
- e -> result.setText(
- computeResult(
- (Operation) operations.getValue(),
- input[0].getText(),
- input[1].getText()
- )
- )
- );
- HBox box = new HBox();
- box.getChildren().addAll(
- input[0], operations, input[1], calculate, result
- );
- Group root = new Group();
- root.getChildren().add(box);
- final Scene scene = new Scene(root);
- //apply your css for the styling
- scene.getStylesheets().add("http://pastebin.com/raw.php?i=wxn9WiVf");
- scene.setFill(Color.WHITE);
- stage.initStyle(StageStyle.UTILITY);
- stage.setScene(scene);
- stage.sizeToScene();
- stage.centerOnScreen();
- stage.show();
- }
- private String computeResult(Operation op, String val1, String val2) {
- double result = op.apply(
- Double.parseDouble(val1),
- Double.parseDouble(val2)
- );
- return result == (int) result
- ? String.valueOf((int) result)
- : String.format("%.2f", result);
- }
- enum Operation implements BinaryOperator<Double>{
- ADD((x, y) -> x + y),
- SUBTRACT((x, y) -> x - y),
- MULTIPLY((x, y) -> x * y),
- DIVIDE((x, y) -> x / y),
- MOD((x, y) -> x % y),
- HYPOTENUSE(Math::hypot),
- EXPONENTIATE(Math::pow);
- private final BinaryOperator<Double> equation;
- Operation(BinaryOperator<Double> equation) {
- this.equation = equation;
- }
- // public Equation getEquation() {
- // return this.equation;
- // }
- @Override
- public String toString() {
- return this.name().charAt(0) + this.name().substring(1).toLowerCase();
- }
- @Override
- public Double apply(Double t, Double u) {
- return equation.apply(t, u);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement