我正在尝试创建一个 JavaFX 程序来管理生产线。我正在使用数据库,以便用户可以使用 TextField
和 ChoiceBox
填充数据库。我在从我创建的 Enum 类填充 ChoiceBox
时遇到问题。
预计我的 ChoiceBox
会填充 Enum
类中的项目,但是 ChoiceBox
保持空白。代码正在编译。
在您向我推荐this link之前,我尝试使用该讨论中的建议,但我无法理解它。该讨论没有帮助,因为我不确定他们试图在哪里填充他们的ComboBox
。另外,cbxStatus.getItems().setAll(Status.values());
对我不起作用(我可能错误地应用了它)。
我的枚举类:
package sample;
public enum ItemType {
AUDIO("AU"),
VISUAL("VI"),
AUDIOMOBILE("AM"),
VISUALMOBILE("VM");
final String itemType;
ItemType(String itemType) {
this.itemType = itemType;
}
public String getItemType() {
return itemType;
}
}
我的 Controller 类:
package sample;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import java.sql.SQLException;
public class Controller {
@FXML
private TextField productName;
@FXML
private TextField productManufacturer;
@FXML
private ChoiceBox<ItemType> itemType = new ChoiceBox<>();
private DatabaseManager databaseManager = new DatabaseManager();
public Controller() throws SQLException {
}
@FXML
public void initialize() {
itemType.getItems().setAll(ItemType.values());
}
public void addProduct() {
String name = productName.getText();
String manufacturer = productManufacturer.getText();
String type = itemType.toString();
databaseManager.insert(type, manufacturer, name);
System.out.println("Button Pressed");
}
public void recordProduction(ActionEvent actionEvent) {
System.out.println("Button Pressed");
}
}
最后,填充 ChoiceBox
后,我需要捕获用户的选择以输入到我的数据库中。类似于 String type = itemType.toString();
。
最佳答案
我认为您错过了显而易见的事情并思考新事物,Enum
就是问题所在。
@FXML
private ChoiceBox<ItemType> itemType = new ChoiceBox<>();
您的 Controller 的字段可以访问一个 ChoiceBox 实例,而表单上的实例是不同的。您从未将项目添加到与之交互的选择框中。
关于java - 如何用单独的枚举类填充JavaFX ChoiceBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58532041/