gpt4 book ai didi

java - 更新 javafx 中突出显示的单元格

转载 作者:行者123 更新时间:2023-12-01 12:45:15 24 4
gpt4 key购买 nike

我使用两个文本字段和一个按钮将条目添加到两列表格中。

如果我添加新条目,表格会立即更新:

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());
}
}

在初始化方法中,我将一个监听器添加到可观察列表中:

final ObservableList<Test> t1 = testTable.getSelectionModel().getSelectedItems();
t1.addListener(selector);

我的测试类(class):

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();
}
}

如何让“编辑”按钮立即更新单元格值?

最佳答案

假设您使用 PropertyValueFactory 作为表格列的单元格工厂,则需要提供属性访问器方法,以便 PropertyValueFactory 提供的表格单元格可以监听这些属性的变化。

使用 JavaFX 属性模型的一个正确实现如下所示

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这说明了问题所在。

关于java - 更新 javafx 中突出显示的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24767234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com