【发布时间】:2018-12-02 13:44:19
【问题描述】:
我正在尝试使用 GUI 中的 TableView 在 JavaFx 中制作披萨订购系统。我终于让它工作了,但现在我在布局上有点挣扎。我无法让我的 observablearraylist 的内容只显示按钮?
public class PizzaOrderingSystem extends Application {
private final TableView<MenuItem> table = new TableView<>();
private final ObservableList<MenuItem> ObservableList =
FXCollections.observableArrayList();
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
stage.setTitle("Pizza Ordering System");
stage.setWidth(600);
stage.setHeight(600);
setTableappearance();
fillTableViewObservableListWithSampleMenuItem();
table.setItems(ObservableList);
//Name column
TableColumn<MenuItem, String> nameColumn = new TableColumn<>("Name of item");
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
//Price column
TableColumn<MenuItem, Double> priceColumn = new TableColumn<>("Price of item");
priceColumn.setCellValueFactory(new PropertyValueFactory<>("price"));
table.getColumns().addAll(nameColumn, priceColumn);
addButtonToTable();
Scene scene = new Scene(new Group(table));
stage.setScene(scene);
stage.show();
}
private void setTableappearance() {
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table.setPrefWidth(600);
table.setPrefHeight(600);
}
private void fillTableViewObservableListWithSampleMenuItem() {
ObservableList.addAll(new Pizza("Margherita", 50),
new Pizza("Hawaii", 55),
new Pizza("Marinara", 70),
new Pizza("Meat Lovers", 70),
new Pizza("Calazone", 60),
new Burger("Burger", 60),
new Burger("Cheeseburger", 65),
new Burger("Baconburger", 65),
new Soda("Coca cola", 25),
new Soda("Coca cola light", 25),
new Soda("Fanta", 25),
new Soda("Faxe kondi", 25));
}
private void addButtonToTable() {
TableColumn<MenuItem, Void> button = new TableColumn("Select your items");
Callback<TableColumn<MenuItem, Void>, TableCell<MenuItem, Void>>
cellFactory = new Callback<TableColumn<MenuItem, Void>, TableCell<MenuItem, Void>>() {
@Override
public TableCell<MenuItem, Void> call(final TableColumn<MenuItem, Void> param) {
final TableCell<MenuItem, Void> cell = new TableCell<MenuItem, Void() {
private final Button button = new Button("Select");
{
button.setOnAction((ActionEvent event) -> {
MenuItem menuItem = getTableView().getItems().get(getIndex());
System.out.println("selectedMenuItem: " + menuItem);
});
}
@Override
public void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
setGraphic(button);
}
}
};
return cell;
}
};
button.setCellFactory(cellFactory);
table.getColumns().add(button);
}
}
【问题讨论】:
-
在您的代码中看不到任何按钮(顺便说一句,它不是minimal reproducible example,因为它应该尽可能轻松地帮助您:) 确保有可能,您需要一个自定义的 tableCell,它有一个按钮并将其连接起来以做任何你想做的事情 - 搜索这个网站,有很多关于确切过程的例子。
-
嗨,Kleopatra,我只是非常不知道该怎么做,所以我只是希望得到一些指导。我终于在我的 tableView 中获得了按钮,但现在我无法附加我的 ObservableArrayList,由于某种原因,它只是显示按钮,而不是 ArrayList 的内容。我更改了上面的代码。最好的问候多特
-
我刚刚开始工作!在文档中输入了工作代码。
-
您可以发布自己问题的答案
-
很高兴你找到了解决方案 :)