【问题标题】:JavaFX: adding text and progressBar in same cell of TableViewJavaFX:在 TableView 的同一单元格中添加文本和进度条
【发布时间】:2020-02-05 11:30:36
【问题描述】:
是否可以将文本和进度条放在同一个单元格中?我目前有基于字符串的单元格,但我还想添加一些具有字符串和进度条的单元格。下面的(坏的)绘图就是一个例子:
我想这样做,因为有些项目会在准备好选择之前显示在列表中(仍在创建与它们对应的文件)。但是有些会准备好选择,所以我试图避免单独的进度列,因为这需要根据所有项目是否准备好突然出现和消失。我也希望没有进度条的项目是字符串单元格(但如果这不可能,那么我可以即兴创作)。
这是否可能,如果没有,关于我想要实现的任何有用的建议。
谢谢:)
【问题讨论】:
标签:
java
uitableview
javafx
tableview
【解决方案1】:
代码示例展示了如何将任何内容放入表格列单元格中。
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
public class TableViewApp extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws Exception {
ObservableList<Employee> employees = FXCollections.observableArrayList(new Employee("John"), new Employee("Michael"));
TableView<Employee> tableView = new TableView<>(employees);
TableColumn<Employee, String> nameColumn = new TableColumn<>("Name");
nameColumn.setCellFactory(param -> new TableCell<Employee, String>() {
private final EmployeeNameCell employeeNameCell = new EmployeeNameCell();
@Override
protected void updateItem(String name, boolean empty) {
super.updateItem(name, empty);
if (name == null || empty) {
setGraphic(null);
} else {
employeeNameCell.setName(name);
setGraphic(employeeNameCell);
}
}
});
nameColumn.setCellValueFactory(param -> param.getValue().nameProperty());
tableView.getColumns().add(nameColumn);
Scene scene = new Scene(tableView);
stage.setScene(scene);
stage.show();
}
}
class Employee {
private final StringProperty nameProperty = new SimpleStringProperty();
public Employee(String name) {
nameProperty.set(name);
}
public StringProperty nameProperty() {
return nameProperty;
}
}
class EmployeeNameCell extends HBox {
private final TextField textField = new TextField();
private final StringProperty nameProperty = new SimpleStringProperty();
public EmployeeNameCell() {
getChildren().add(textField);
setMaxWidth(10e6);
setHgrow(textField, Priority.ALWAYS);
nameProperty.addListener((ChangeListener<String>) (observable, oldValue, newValue) -> {
textField.setText(newValue);
});
}
public void setName(String name) {
nameProperty.set(name);
}
}