我是javafx的新人,但我正在编写一个应用程序,我希望我的#34;到#34;要根据选择框中选择的选项进行更改,但我当前的代码始终将其保持为0..help?我希望能够根据状态更改为
public void start(Stage primaryStage) {
double to=0;
primaryStage.setTitle("ShCal");
GridPane pane = new GridPane();
` pane.setAlignment(Pos.CENTER);
pane.setHgap(10);
pane.setVgap(10);
pane.setPadding(new Insets(25, 25, 25, 25));
Scene scene = new Scene(pane, 300, 275);
//button
Button button=new Button("to");
pane.add(button, 0, 3);
//Pick state
Label State=new Label("State");
pane.add(State,0,0);
//choicebox
ChoiceBox<String> choicesBox=new ChoiceBox<>();
choicesBox.getItems().addAll("NJ","NY");
pane.add(choicesBox,1,0);
//set default
choicesBox.setValue(null);
button.setOnAction(e->getChoice(choicesBox,to));
primaryStage.setScene(scene);
primaryStage.show();
}
private double getChoice(ChoiceBox<String> choicesBox, double tx) {
String state=choicesBox.getValue();
System.out.print(tx);
if(state=="NJ")
{
tx=10/100;
}
System.out.print(state);
return tx;
}
public static void main(String[] args) {
launch(args);
}
}
答案 0 :(得分:1)
这是因为您的to
值是基本类型double,在start
方法的范围内定义。方法getChoice
返回新值,但您没有更新它。
您可以尝试以下两种方法:
将to
定义为成员:
private double to = 0;
private double getChoice(ChoiceBox<String> choicesBox) {
String state=choicesBox.getValue();
if(state=="NJ") {
tx=10/100;
}
}
但是我个人更喜欢与JavaFX更为内联的解决方案:将to
变量定义为成员属性:
private DoubleProperty to = new SimpleDoubleProperty(0);
private double getChoice(ChoiceBox<String> choicesBox) {
String state=choicesBox.getValue();
if(state=="NJ") {
tx.setValue(10/100);
}
}
这样做可以让你有一个显示价值的标签,而无需在每次更改时更新它:
Label lbl = new Label();
lbl.textProperty().bind(to.asString());