目前我有一个模型程序here。
我想要发生的是当用户输入当前在表格中显示的名称并点击"更改"按钮,它将改变" Status"指定名称的项目/行的列文本到另一个文本,例如"正在运行"
我目前有以下代码:
Controller.java
public class Controller implements Initializable {
@FXML
TableView<TableRow> tableView;
@FXML
TableColumn<TableRow, String> tbc_name;
@FXML
TableColumn<TableRow, String> tbc_status;
ObservableList<TableRow> rows = FXCollections.observableArrayList();
@Override
public void initialize(URL location, ResourceBundle resources) {
tbc_name.setCellValueFactory(new PropertyValueFactory<TableRow, String>("name"));
tbc_status.setCellValueFactory(new PropertyValueFactory<TableRow, String>("status"));
tableView.getItems().setAll(gettableRows());
System.out.println("started");
}
public ObservableList<TableRow> gettableRows() {
rows.add(new TableRow("Name1", "none"));
rows.add(new TableRow("Name2", "none"));
rows.add(new TableRow("Name3", "none"));
return rows;
}
}
TableRow.java
public class TableRow {
private String name;
private String status;
public TableRow(){
this.name = "";
this.status = "";
}
public TableRow(String name_, String status_){
name = name_;
status = status_;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
为了更好地理解我想要实现的目标,在C#
我可以使用以下代码更改列表视图中特定单元格的文本:
ListViewItem lvi = listview1.FindItemWithText(username);
lvi.Subitems[3].Text = "Running...";
感谢任何帮助。
答案 0 :(得分:3)
如果你有一个模型类来表示tableView中的一行,那么你可以将它用作cellValueFactory,所以重构这些行:
tbc_name.setCellValueFactory(new PropertyValueFactory<TableRow, String>("name"));
tbc_status.setCellValueFactory(new PropertyValueFactory<TableRow, String>("status"));
为:
tbc_name.setCellValueFactory(data -> data.getValue().nameProperty());
tbc_status.setCellValueFactory(data -> data.getValue().statusProperty());
并将TableRow类重构为:
public class TableRow {
private StringProperty name;
private StringProperty status;
public TableRow(String name, String status) {
this.name = new SimpleStringProperty(name);
this.status = new SimpleStringProperty(status);
}
public String getName() {
return name.get();
}
public StringProperty nameProperty() {
return name;
}
public String getStatus() {
return status.get();
}
public StringProperty statusProperty() {
return status;
}
public void setStatus(String status) {
this.status.set(status);
}
}
然后你必须用textField(更改按钮上方的Textfield)和一个按钮(Change)扩展控制器。
change.setOnAction(action ->{
String text = changeTextField.getText();
tableView.getItems().stream()
.filter(row -> row.getName().equals(text))
.findFirst()
.ifPresent(row -> row.setStatus("Running"));
});