我使用两个文本字段和一个按钮将条目添加到两列表中。
如果我添加新条目,表格会立即更新:
private void addBtn(ActionEvent event) {
Test o = new Test();
o.setTitle(title.getText());
o.setCount(Integer.parseInt(count.getText()));
mainApp.getData().add(o);
}
在第二步中,我添加了一个额外的按钮来修改突出显示的计数单元格:
private void editBtn(ActionEvent event) {
Test o = getSelection();
o.setCount(Integer.parseInt(count.getText()));
mainApp.getData().set(tablePosition, o);
}
如果单击该按钮,单元格将更新该值,但在表格中不可见。如果我再次单击该按钮,它将更新表格。
要检查突出显示哪一行,请使用以下功能:
private final ListChangeListener<Test> selector = new ListChangeListener<Test>() {
@Override
public void onChanged(ListChangeListener.Change<? extends Test> c) {
setSelection();
}
};
public Test getSelection() {
if (testTable != null) {
List<Test> table = testTable.getSelectionModel().getSelectedItems();
if (table.size() == 1) {
final Test selection = table.get(0);
return selection;
}
}
return null;
}
private void setSelection() {
final Test o = getSelection();
tablePosition = mainApp.getData().indexOf(o);
if (o != null) {
title.setText(o.getTitle());
count.setText(o.getCount().toString());
}
}
在initialize方法中,我将一个监听器添加到observable列表中:
final ObservableList<Test> t1 = testTable.getSelectionModel().getSelectedItems();
t1.addListener(selector);
我的测试课程:
public class Test {
private final SimpleStringProperty title = new SimpleStringProperty();
private final SimpleIntegerProperty count = new SimpleIntegerProperty();
public void setTitle(String title) {
this.title.set(title);
}
public String getTitle() {
return title.get();
}
public void setCount(Integer count) {
this.count.set(count);
}
public Integer getCount() {
return count.get();
}
}
如何让“编辑”按钮立即更新单元格值?
答案 0 :(得分:1)
假设您使用PropertyValueFactory
作为表列的单元格工厂,则需要提供属性访问器方法,以便PropertyValueFactory
提供的表格单元可以侦听这些属性以进行更改
使用JavaFX Property模型的一个正确实现类似于
public class Test {
private final IntegerProperty count = new SimpleIntegerProperty(this, "count", 0);
private final StringProperty title = new SimpleStringProperty(this, "title", "");
public final int getCount() {
return count.get();
}
public final void setCount(int count) {
this.count.set(count);
}
public IntegerProperty countProperty() {
return count ;
}
public final String getTitle() {
return title.get();
}
public final void setTitle(String title) {
this.title.set(title);
}
public StringProperty titleProperty() {
return title ;
}
}
然后,以下方法将正确更新表中的选定行:
private void editBtn(ActionEvent event) {
Test o = testTable.getSelectionModel().getSelectedItem();
if (o != null) {
o.setCount(Integer.parseInt(count.getText()));
}
}
如果这不能解决您的问题,我建议您完全修改问题并提供一个sscce来说明问题。