我正在使用Text对象填充ComboBox。使用Text对象而不是Strings允许我添加一个id值,我可以在我的程序中使用它,并在我决定国际化UI时使用。无论如何,这是我正在做的事情: 主要课程:
public class MainApp extends Application {
private Stage primaryStage;
@Override
public void start(Stage primaryStage) {
this.primaryStage = primaryStage;
try {
AnchorPane paneMain = (AnchorPane) FXMLLoader.load(getClass().getResource("Test.fxml"));
Scene scene = new Scene(paneMain);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
控制器:
public class Test implements Initializable{
@FXML
private AnchorPane anchorPane;
@FXML
private ComboBox<Text> comboTime;
private Text days;
private Text hours;
private Text minutes;
private int timeMultiplier;
public Test(){
days = new Text("Days");
days.setId("86400000");
hours = new Text("Hours");
hours.setId("3600000");
minutes = new Text("Minutes");
minutes.setId("3600000");
timeMultiplier = 0;
}
@Override
public void initialize(URL location, ResourceBundle resources) {
comboTime.getItems().removeAll(comboTime.getItems());
comboTime.getItems().addAll(days, hours, minutes);
comboTime.getSelectionModel().select(hours);
}
@FXML
private void setTimeMultiplier(){
Text text = comboTime.getSelectionModel().getSelectedItem();
timeMultiplier = Integer.valueOf(text.getId());
}
}
Test.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.collections.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>
<AnchorPane id="AnchorPane" fx:id="anchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="100.99990000000253" prefWidth="94.99990000000253" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="com.spacitron.backupp.ui.controllers.Test">
<children>
<HBox id="HBox" alignment="CENTER" layoutX="41.0" layoutY="224.0" prefWidth="216.0" spacing="5.0" />
<ComboBox id="comboInterval" fx:id="comboTime" editable="false" layoutX="14.0" layoutY="22.0" onAction="#setTimeMultiplier">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="Item 1" />
<String fx:value="Item 2" />
<String fx:value="Item 3" />
</FXCollections>
</items>
</ComboBox>
</children>
</AnchorPane>
现在,这很好用。但问题是,当我选择一个项目时,该项目上的文字会变成空白,如下所示:
如果我选择另一个,那也会消失:
我仍然可以选择这些项目,但它们只是没有被人看到。这是一个错误,如果有的话有办法解决吗?
已编辑以提供MCVE