我只是在学习JavaFX和看教程。这是大量的信息需要处理,所以我开始从一个简单的BMI计算器应用程序。Im不包括BMI类,但它有一个构造函数:BMI(双高、双重、字符串性别)
问题:
总之,用户应该在输入3个值后按下“计算”按钮,然后我将使用我的Bmi类创建一个Bmi,并在一个新的框中显示该Bmi的值。(我将不得不添加Bmi的框)稍后显示。
Get Eventhandler工作,能够接受文本字段的值(比如扫描仪),创建一个新的Bmi,创建一个新的框,在这里我将显示那个Bmi的值。(我在我的BMI类中得到了计算BMI的方法。
public class Main extends Application {
Button b1;
Button b2;
Text g;
Text w;
Text h;
TextField g1;
TextField w1;
TextField h1;
@Override
public void start(Stage stage) throws Exception{
g = new Text("Gender:");
w = new Text("Weight:");
h = new Text("Height");
g1 = new TextField();
w1 = new TextField();
h1 = new TextField();
b1 = new Button("Calculate BMI!");
b2 = new Button("Reset BMI");
GridPane grid = new GridPane();
grid.setMinSize(400, 200);
grid.setPadding(new Insets(10, 10, 10, 10));
grid.setVgap(5);
grid.setHgap(5);
grid.setAlignment(Pos.CENTER);
grid.add(g, 0, 0);
grid.add(g1, 1, 0);
grid.add(w, 0, 1);
grid.add(w1, 1, 1);
grid.add(h, 0, 2);
grid.add(h1, 1, 2);
grid.add(b1, 0, 3);
grid.add(b2, 1, 3);
b1.setStyle("-fx-background-color: purple; -fx-text-fill: white;");
b2.setStyle("-fx-background-color: purple; -fx-text-fill: white;");
grid.setStyle("-fx-background-color: GREEN;");
Scene scene = new Scene(grid);
stage.setScene(scene);
stage.show();
}
public void handle(ActionEvent event){
if(event.getSource() == b1){
//do something
}
}
public static void main(String[] args) {
launch(args);
}}发布于 2019-02-11 20:59:46
似乎您有处理操作事件的方法,但是处理程序本身从未附加到按钮或文本字段。为此,您需要提供一个EventHandler接口实现,例如:
button.addEventHandler(ActionEvent.ACTION, (ActionEvent event) -> {
// your code here
});有关更多详细信息,请参阅使用事件处理程序。
但是,正如@kleopatra所提到的,更好的做法是使用适当的setOnXxx()方法提供事件处理程序,例如:
button.setOnAction((ActionEvent event) -> {
// your code here
});你也知道如何像扫描仪一样“收集”文本文件中的用户输入,然后用它们创建一个新的Bmi,最后在一个新的框或类似的地方显示这个数字。
这里是您需要确定业务模型的部分,以便生成包含来自控件的数据的一个或多个类。一个好的候选人是BmiData POJO,如下所示:
public class BmiData {
private String gender;
private Double height;
private Double weight;
// Constructor, getters and setters
public Double calculateBmi() {
// perform the calculation here
}
}然后,附加在“计算体重指数”按钮上的事件处理程序是将文本字段中的数据收集到BmiData对象中并最终将结果显示给用户的良好选择。我建议您研究MVC ()设计模式。
https://stackoverflow.com/questions/54638770
复制相似问题