JavaFX初学者的简单计算器事件处理

JavaFX begginer's simple calculator event handling

嘿,我是 java 的初学者,我只做了很短的时间,无论如何,对于我在 java 基础知识中的最终项目,我需要做一个简单的带有图形用户界面的计算器,我认为它不会那么难,但我有点错了 :P 我已经设法做了最多的事情(我认为)但是我被 atm 困在操作的事件处理和设置计算值,这是我的代码,你能给我一些建议或提示吗 :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");
    }
}

我的处理程序只是基本处理程序,它们将数字打印到控制台中,因此您可以忽略它们,我看到了一些带有 value.set 命令的示例,我应该使用它们还是?请帮助截止日期为 2 周。非常感谢

我不会给你做功课,只是一些提示:

  • 变量名应以小写字母开头(TextField rezultat,而不是 Rezultat)

想一想当您按下按钮时您期望发生什么:

  • 如果您按 5 '-' '+' 55,您的计算器应该做什么。它应该从 5 中减去还是添加 55)
  • 您要计算不止一个操作吗? (5+5+5+5/5)
  • 十进制数呢? (你现在的设计可以不填)

你对每个按钮做几乎相同的事情。(或者至少对 10 个按钮你有相同的逻辑) 您可以循环创建应用程序:

 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);

}

}

public class 查看扩展应用程序{

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 型号 {

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 控制器 {

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();
}

}