JavaFX begginer's simple calculator event handling

只谈情不闲聊 提交于 2019-12-12 03:35:42

问题


Hey I'm a begginer at java and i've only been doing this for a short period of time, anyways for my final project in java basics i need to make a simple calculator with a gui, i thought it won't be that hard but i was kinda wrong :P i have managed to do the most (i think) but am stuck atm with the event handling for the operations and setting the value to calculate, here is my code and could you please give me suggestions or tips on how to do it :D

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.value.WritableObjectValue;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;



public class Calculator extends Application {

    private DoubleProperty value = new SimpleDoubleProperty();

    @Override
    public void start(Stage primaryStage) {

        FlowPane pane = new FlowPane();
        pane.setAlignment(Pos.CENTER);
        pane.setPadding(new Insets ( 30 , 20 , 30 , 20));
        pane.setHgap(5);
        pane.setVgap(5);
        pane.setMinWidth(400);
        pane.setPrefWidth(400);
        pane.setMaxWidth(400);

        TextField Rezultat = new TextField();
        Rezultat.setEditable(false);
        Rezultat.setAlignment(Pos.CENTER);
        Rezultat.setMinSize(336, 40);
        Rezultat.textProperty().bind(Bindings.format("%.0f" , value));
        pane.getChildren().add(Rezultat);

        Button sedmica = new Button("7");           
        Button osmica = new Button("8");
        Button devetka = new Button("9");
        Button plus = new Button("+");

            sedmica.setMinSize(80, 80);
            osmica.setMinSize(80, 80);
            devetka.setMinSize(80, 80);
            plus.setMinSize(80, 80);

    pane.getChildren().add(sedmica);
        sedmicaHandler handler7 = new sedmicaHandler();
        sedmica.setOnAction(handler7);
    pane.getChildren().add(osmica);
        osmicaHandler handler8 = new osmicaHandler();
        osmica.setOnAction(handler8);
    pane.getChildren().add(devetka);
        devetkaHandler handler9 = new devetkaHandler();
        devetka.setOnAction(handler9);
    pane.getChildren().add(plus);
        plusHandler handlerplus = new plusHandler();
        plus.setOnAction(handlerplus);

        Button cetvorka = new Button("4");
        Button petica = new Button("5");
        Button sestica = new Button("6");
        Button minus = new Button("-");

            cetvorka.setMinSize(80, 80);
            petica.setMinSize(80, 80);
            sestica.setMinSize(80, 80);
            minus.setMinSize(80, 80);

    pane.getChildren().add(cetvorka);
        cetvorkaHandler handler4 = new cetvorkaHandler();
        cetvorka.setOnAction(handler4);
    pane.getChildren().add(petica);
        peticaHandler handler5 = new peticaHandler();
        petica.setOnAction(handler5);
    pane.getChildren().add(sestica);
        sesticaHandler handler6 = new sesticaHandler();
        sestica.setOnAction(handler6);
    pane.getChildren().add(minus);
        minusHandler handlerminus = new minusHandler();
        minus.setOnAction(handlerminus);

        Button trica = new Button("3");
        Button dvica = new Button("2");
        Button jedinica = new Button("1");
        Button puta = new Button("*");

            trica.setMinSize(80, 80);
            dvica.setMinSize(80, 80);
            jedinica.setMinSize(80, 80);
            puta.setMinSize(80, 80);

    pane.getChildren().add(jedinica);
        jedinicaHandler handler1 = new jedinicaHandler();
        jedinica.setOnAction(handler1);
    pane.getChildren().add(dvica);
        dvicaHandler handler2 = new dvicaHandler();
        dvica.setOnAction(handler2);
    pane.getChildren().add(trica);
        tricaHandler handler3 = new tricaHandler();
        trica.setOnAction(handler3);
    pane.getChildren().add(puta);
        putaHandler handlerputa = new putaHandler();
        puta.setOnAction(handlerputa);

        Button nula = new Button("0");
        Button jednako = new Button("=");
        Button podijeljeno = new Button("/");
        Button EE = new Button ("EE");

            nula.setMinSize(80, 80);
            jednako.setMinSize(80, 80);
            podijeljeno.setMinSize(80, 80);
            EE.setMinSize(80, 80);

    pane.getChildren().add(EE);
        EEHandler handlerEE = new EEHandler();
        EE.setOnAction(handlerEE);
    pane.getChildren().add(nula);
        nulaHandler handler0 = new nulaHandler();
        nula.setOnAction(handler0);
    pane.getChildren().add(jednako);
        jednakoHandler handlerjednako = new jednakoHandler();
        jednako.setOnAction(handlerjednako);
    pane.getChildren().add(podijeljeno);
        podijeljenoHandler handlerpodijeljeno = new podijeljenoHandler();
        podijeljeno.setOnAction(handlerpodijeljeno);



    Scene scene = new Scene(pane);
    primaryStage.setTitle("Calculator");
    primaryStage.setScene(scene);
    primaryStage.show();

    }

    public static void main (String[] args) {
    Application.launch(args);  

    }

}

class nulaHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        value.set(0);
    }
}
class jedinicaHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("1");
    }
}           
class dvicaHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("2");
    }   
}
class tricaHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("3");
    }
}           
class cetvorkaHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("4");
    }
}
class peticaHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("5");
    }
}                   
class sesticaHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("6");
    }
}                       
class sedmicaHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("7");
    }
}                           
class osmicaHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("8");
    }
}                               
class devetkaHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("9");
    }
}                                   
class plusHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("+");
    }
}                                       
class minusHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("-");
    }
}                                           
class putaHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("*");
    }
}
class podijeljenoHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("/");
    }
}                                                   
class jednakoHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("=");
    }
}                                                       
class EEHandler implements EventHandler<ActionEvent>{
        @Override
    public void handle(ActionEvent e){
        System.out.println("EE");
    }
}

My handlers are just basic ones, they print the number into the console so you can disregard them, i saw some examples with the value.set commands should i go with them or ? please help deadline is in 2 weeks. Thanks a lot


回答1:


I will not do the homework for you, but just a few tips:

  • variable-names should start with a lowercase letter (TextField rezultat, not Rezultat)

think about what exactly you expect to happen when you press the buttons:

  • what should your calculator do, if you press 5 '-' '+' 55. should it subtract or add 55 from 5)
  • do you want to calculate more than one operation? (5+5+5+5/5)
  • what about decimal numbers? (you can not fill them in, at your current design)

And you do nearly the same thing for every button.(or at least for 10 buttons you have the same logic) you can create your application in a loop:

 public class Calculator extends Application {

 private TextField textField = new TextField(); 

 @Override
 public void start(Stage primaryStage) {

    List<String> buttons = Arrays.asList("7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", "0", "=", "/", "EE");

    FlowPane pane = new FlowPane();
    pane.setAlignment(Pos.CENTER);
    pane.setPadding(new Insets(30, 20, 30, 20));
    pane.setHgap(5);
    pane.setVgap(5);
    pane.setMinWidth(400);
    pane.setPrefWidth(400);
    pane.setMaxWidth(400);

    textField.setEditable(false);
    textField.setAlignment(Pos.CENTER);
    textField.setMinSize(336, 40);
    // Rezultat.textProperty().bind(Bindings.format("%.0f", value));
    pane.getChildren().add(textField);

    for (String button : buttons) {
        Button b = new Button(button);
        b.setMinSize(80, 80);
        pane.getChildren().add(b);
        b.setOnAction((e) -> doSomething(b.getText()));
    }

    Scene scene = new Scene(pane);
    primaryStage.setTitle("Calculator");
    primaryStage.setScene(scene);
    primaryStage.show();

}

private void doSomething(String text) {

    if (text.equalsIgnoreCase("=")) {
        // Calc
    }

    else if (text.equalsIgnoreCase("EE")) {
        // EE
    } else if (text.equalsIgnoreCase("+") || text.equalsIgnoreCase("-") || text.equalsIgnoreCase("*") || text.equalsIgnoreCase("/")) {
        // + - * /
    }
    // ....
    else {
        // numeric
        textField.appendText(text);
    }
}

public static void main(String[] args) {
    Application.launch(args);

}

}



回答2:


public class View extends Application{

public static void main(String[] args) {
    launch(args);
}

public void start(Stage primaryStage){
    primaryStage.setTitle("Calculator");

    GridPane root = new GridPane();

    Label textBox1 = new Label("Text1");
    root.add(textBox1, 0, 0, 5, 1);
    Label textBox2 = new Label("Text2");
    root.add(textBox2, 0, 1, 5, 1);
    textBox1.setId("lblTextBox1");
    textBox2.setId("lblTextBox2");

    Button btn0 = new Button("0");
    Button btn1 = new Button("1");
    Button btn2 = new Button("2");
    Button btn3 = new Button("3");
    Button btn4 = new Button("4");
    Button btn5 = new Button("5");
    Button btn6 = new Button("6");
    Button btn7 = new Button("7");
    Button btn8 = new Button("8");
    Button btn9 = new Button("9");
    btn0.setId("btn0");
    btn1.setId("btn1");
    btn2.setId("btn2");
    btn3.setId("btn3");
    btn4.setId("btn4");
    btn5.setId("btn5");
    btn6.setId("btn6");
    btn7.setId("btn7");
    btn8.setId("btn8");
    btn9.setId("btn9");


    Button btnDot = new Button(".");
    Button btnPlus = new Button("+");
    Button btnMinus = new Button("-");
    Button btnTimes = new Button("*");
    Button btnDivide = new Button("/");
    Button btnEquals = new Button("=");
    Button btnMC = new Button("MC");
    Button btnMR = new Button("MR");
    Button btnMS = new Button("MS");
    Button btnMPlus = new Button("M+");
    Button btnMMinus = new Button("M-");
    Button btnBack = new Button("<=");
    Button btnCE = new Button("CE");
    Button btnC = new Button("C");
    Button btnPlusOrMinus = new Button("+/-");
    Button btnSqrt = new Button("sqrt");
    Button btnPercentage= new Button("%");
    Button btn1OverX = new Button("1/x");
    btnPlus.setId("btnPlus");
    btnTimes.setId("btnTimes");
    btnDot.setId("btnDot");
    btnEquals.setId("btnEquals");
    btnC.setId("btnClear");

    btn0.setMaxHeight(Double.MAX_VALUE);
    btn0.setMaxWidth(Double.MAX_VALUE);

    btn1.setMaxHeight(Double.MAX_VALUE);
    btn1.setMaxWidth(Double.MAX_VALUE);

    btn2.setMaxHeight(Double.MAX_VALUE);
    btn2.setMaxWidth(Double.MAX_VALUE);

    btn3.setMaxHeight(Double.MAX_VALUE);
    btn3.setMaxWidth(Double.MAX_VALUE);

    btn4.setMaxHeight(Double.MAX_VALUE);
    btn4.setMaxWidth(Double.MAX_VALUE);

    btn5.setMaxHeight(Double.MAX_VALUE);
    btn5.setMaxWidth(Double.MAX_VALUE);

    btn6.setMaxHeight(Double.MAX_VALUE);
    btn6.setMaxWidth(Double.MAX_VALUE);

    btn7.setMaxHeight(Double.MAX_VALUE);
    btn7.setMaxWidth(Double.MAX_VALUE);

    btn8.setMaxHeight(Double.MAX_VALUE);
    btn8.setMaxWidth(Double.MAX_VALUE);

    btn9.setMaxHeight(Double.MAX_VALUE);
    btn9.setMaxWidth(Double.MAX_VALUE);

    btnEquals.setMaxHeight(Double.MAX_VALUE);
    btnEquals.setMaxWidth(Double.MAX_VALUE);

    btnMC.setMaxHeight(Double.MAX_VALUE);
    btnMC.setMaxWidth(Double.MAX_VALUE);

    btnMMinus.setMaxHeight(Double.MAX_VALUE);
    btnMMinus.setMaxWidth(Double.MAX_VALUE);

    btnPlusOrMinus.setMaxHeight(Double.MAX_VALUE);
    btnPlusOrMinus.setMaxWidth(Double.MAX_VALUE);

    btnPercentage.setMaxHeight(Double.MAX_VALUE);
    btnPercentage.setMaxWidth(Double.MAX_VALUE);

    btnSqrt.setMaxHeight(Double.MAX_VALUE);
    btnSqrt.setMaxWidth(Double.MAX_VALUE);

    btn1OverX.setMaxHeight(Double.MAX_VALUE);
    btn1OverX.setMaxWidth(Double.MAX_VALUE);

    btnPlus.setMaxHeight(Double.MAX_VALUE);
    btnPlus.setMaxWidth(Double.MAX_VALUE);

    btnMinus.setMaxHeight(Double.MAX_VALUE);
    btnMinus.setMaxWidth(Double.MAX_VALUE);

    btnTimes.setMaxHeight(Double.MAX_VALUE);
    btnTimes.setMaxWidth(Double.MAX_VALUE);

    btnDivide.setMaxHeight(Double.MAX_VALUE);
    btnDivide.setMaxWidth(Double.MAX_VALUE);

    btnCE.setMaxHeight(Double.MAX_VALUE);
    btnCE.setMaxWidth(Double.MAX_VALUE);

    btnC.setMaxHeight(Double.MAX_VALUE);
    btnC.setMaxWidth(Double.MAX_VALUE);

    btnDot.setMaxHeight(Double.MAX_VALUE);
    btnDot.setMaxWidth(Double.MAX_VALUE);

    root.add(btnMC,0,1);
    root.add(btnMR,1,1);
    root.add(btnMS,2,1);
    root.add(btnMPlus,3,1);
    root.add(btnMMinus,4,1);

    root.add(btnBack,0,2);
    root.add(btnCE,1,2);
    root.add(btnC,2,2);
    root.add(btnPlusOrMinus,3,2);
    root.add(btnSqrt,4,2);

    root.add(btn7,0,3);
    root.add(btn8,1,3);
    root.add(btn9,2,3);
    root.add(btnDivide,3,3);
    root.add(btnPercentage,4,3);

    root.add(btn4,0,4);
    root.add(btn5,1,4);
    root.add(btn6,2,4);
    root.add(btnTimes,3,4);
    root.add(btn1OverX,4,4);

    root.add(btn1,0,5);
    root.add(btn2,1,5);
    root.add(btn3,2,5);
    root.add(btnMinus,3,5);
    root.add(btnEquals,4,5,1,2);

    root.add(btn0,0,6,2,1);
    root.add(btnDot,2,6);
    root.add(btnPlus,3,6);

    root.setVgap(5);
    root.setHgap(5);
    root.setPadding(new Insets(5,5,5,5));
    primaryStage.setScene(new Scene(root));
    primaryStage.show();


    Controller controller = new Controller(primaryStage.getScene());

}

}

public class Model {

SimpleDoubleProperty totalResult = new SimpleDoubleProperty(0);
SimpleDoubleProperty curNumber = new SimpleDoubleProperty(0);
SimpleStringProperty stringDisplayed = new SimpleStringProperty();
String operatorPressed  = "";
Boolean isDecimal = false;
int decimalCouter = 0;

public void plusOperator(){
    calculate();
    operatorPressed = "+";
}

public void calculate(){
    switch (operatorPressed){
        case "+" :
            totalResult.set(totalResult.get()+ curNumber.get());
            stringDisplayed.set(stringDisplayed.get()+" + " +curNumber.get());
            break;
        case "*" :
            totalResult.set(totalResult.get()*curNumber.get());
            stringDisplayed.set(stringDisplayed.get()+" * " +curNumber.get());
            break;
        default:
            totalResult.set(curNumber.get());
            stringDisplayed.set(curNumber.get()+"");
    }
    curNumber.set(0);
    operatorPressed = "";
    isDecimal = false;
    decimalCouter = 0;
}

public void multiplyOperator(){
    calculate();
    operatorPressed = "*";
}

public void equalsOperator(){
    calculate();
    curNumber.setValue(totalResult.get());
    totalResult.set(0);
}

public void clearOperator(){
    totalResult.setValue(0);
    curNumber.setValue(0);
    stringDisplayed.set("");
    decimalCouter = 0;
    isDecimal = false;
}

public void pressedNumber(int number){


    if(!isDecimal){
        curNumber.setValue(curNumber.get()*10+number);
    }
    else{
        decimalCouter++;
        Double tempCurrentNum = curNumber.get();
        tempCurrentNum = tempCurrentNum*Math.pow(10,decimalCouter);
        tempCurrentNum = tempCurrentNum+number;
        tempCurrentNum = tempCurrentNum*Math.pow(10,-decimalCouter);
        curNumber.set(tempCurrentNum);

    }
}

public void dotOperator(){
    isDecimal = true;
}

}

public class Controller {

Model newModel = new Model();


Controller(Scene scene){
    Button btnPlus, btnTimes, btnEquals, btnClear, btnDot;
    Label textBox1, textBox2;

    for(int ii=0;ii<=9;ii++){
        Button button = (Button)scene.lookup("#btn"+ii);
        int finalIi = ii;
        button.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                pressedNumber(finalIi);
            }
        });
    }

    btnPlus = (Button)scene.lookup("#btnPlus");
    btnTimes = (Button)scene.lookup("#btnTimes");
    btnEquals = (Button)scene.lookup("#btnEquals");
    btnDot = (Button)scene.lookup("#btnDot");
    btnClear = (Button)scene.lookup("#btnClear");

    textBox1 = (Label)scene.lookup("#lblTextBox1");
    textBox2 = (Label)scene.lookup("#lblTextBox2");

    btnPlus.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            plusOperator();
        }
    });

    btnTimes.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            multiplyOperator();
        }
    });

    btnEquals.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            equalsOperator();
        }
    });

    btnClear.setOnMouseClicked(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            clearOperator();
        }
    });

    btnDot.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            dotOperator();
        }
    });

    textBox1.textProperty().bind(newModel.stringDisplayed);
    textBox2.textProperty().bind(newModel.curNumber.asString());


}

public void pressedNumber(int number){
    newModel.pressedNumber(number);
}

public void plusOperator(){
    newModel.plusOperator();
}

public void multiplyOperator(){
    newModel.multiplyOperator();
}

public void equalsOperator(){
    newModel.equalsOperator();
}

public void clearOperator(){
    newModel.clearOperator();
}

public void dotOperator(){
    newModel.dotOperator();
}

}



来源:https://stackoverflow.com/questions/30446996/javafx-begginers-simple-calculator-event-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!