listas jfx desplegable choicebox and javafx

jfx - listas en javafx



Cómo completar una lista de valores a un cuadro combinado en JavaFx (1)

Tengo una lista de valores que quiero completar en un cuadro combinado en javaFx. este es mi combo.xml

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="- Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2"> <children> <ComboBox id="comboId" layoutX="210.0" layoutY="108.0" prefHeight="27.0" prefWidth="102.0" promptText="Select"> <items> <FXCollections fx:factory="observableArrayList"> <String fx:value="Item 1" /> <String fx:value="Item 2" /> <String fx:value="Item 3" /> </FXCollections> </items> </Com boBox> </children> </AnchorPane>

este es mi principal

public class JavaFXExperiment extends Application { @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("combo.fxml")); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); final ComboBox comboId = new ComboBox(); comboId.getItems().addAll( "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"); } public static void main(String[] args) { launch(args); } }

Este es mi archivo xml y la clase principal quiero mostrar esos valores en el combobox. Cualquier persona por favor ayuda


Debe crear un controlador y asignarlo con su pantalla FXML.

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="- Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" fx:controller="MyController" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2"> <children> <ComboBox fx:id="myCombobox" id="comboId" layoutX="210.0" layoutY="108.0" prefHeight="27.0" prefWidth="102.0" promptText="Select"> <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>

Entonces tu clase principal será,

public class JavaFXExperiment extends Application { @Override public void start(Stage stage) throws Exception { FXMLLoader loader = new FXMLLoader(getClass().getResource("combo.fxml")); Parent root = loader.load(); MyController myController = loader.getController(); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); //Set Data to FXML through controller myController.setData(); } public static void main(String[] args) { launch(args); } }

Y su controlador será,

public class MyController implements Initializable { @FXML public Combobox myCombobox; @Override public void initialize(URL url, ResourceBundle rb) { } public void setData(){ myCombobox.getItems().clear(); myCombobox.getItems().addAll( "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"); } }