效果展示
设计Counter类:
package sample;
/**
* Created by shenqianqian on 17/10/14.
*/
public class Counter {
private double num1=0.0;
private double num2=0.0;
private char flag;
public String[] intS;
public Counter(String text){
if(text.contains("+")){//判断输入文本中的计算符号
intS=text.split("\\+");//用正则表达式去掉字符串中的符号
this.flag='+';
this.num1=Integer.parseInt(intS[0]);
this.num2=Integer.parseInt(intS[1]);
}
else if(text.contains("-")){
intS=text.split("\\-");
this.flag='-';
this.num1=Integer.parseInt(intS[0]);
this.num2=Integer.parseInt(intS[1]);
}
else if(text.contains("*")){
intS=text.split("\\*");
this.flag='*';
this.num1=Integer.parseInt(intS[0]);
this.num2=Integer.parseInt(intS[1]);
}
else {
intS=text.split("\\D");
this.flag='/';
this.num1=Integer.parseInt(intS[0]);
this.num2=Integer.parseInt(intS[1]);
}
}
public double getResult(){//计算结果
switch (this.flag){
case '+':
return num1+num2;
case '-':
return num1-num2;
case '*':
return num1*num2;
case '/':
return num1/num2;
default:
return 0;
}
}
}
设计Main类
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main extends Application {
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
// Panel p to hold the label and text field
BorderPane paneForTextField = new BorderPane();
paneForTextField.setPadding(new Insets(5, 5, 5, 5));
paneForTextField.setStyle("-fx-border-color: green");
paneForTextField.setLeft(new Label("请输入: "));
TextField tf = new TextField();
tf.setAlignment(Pos.BOTTOM_RIGHT);
paneForTextField.setCenter(tf);
BorderPane mainPane = new BorderPane();
// Text area to display contents
TextArea ta = new TextArea();
mainPane.setCenter(new ScrollPane(ta));
mainPane.setTop(paneForTextField);
// Create a scene and place it in the stage
Scene scene = new Scene(mainPane, 450, 200);
primaryStage.setTitle("CounterText "); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
tf.setOnAction(event -> {//为文本框设置响应事件
String text=tf.getText();
//正则表达式去除汉字
String reg = "[\u4e00-\u9fa5]";
Pattern pat = Pattern.compile(reg);
Matcher mat=pat.matcher(text);
String rStr = mat.replaceAll("");
Counter counter=new Counter(rStr);
//取结果
double res=counter.getResult();
//文本域展示
ta.setText(rStr+" = "+res+'\n');
});
}
}