【发布时间】:2015-05-05 09:18:07
【问题描述】:
我有一个TableView 的情况。我正在尝试实现一个允许向上或向下移动单元格的功能。向上或向下移动单元格(带有单元格内容)后,我想将焦点更改为单元格的新位置。
问题是它不会更改到新位置。由于某种原因,它停留在原来选定的单元格位置。
这是用于上移、下移和改变焦点的代码:
我正在尝试移动单个选定的单元格。
public class TableController
{
private ObservableList<SimpleStringProperty> observablePrnPropertyData;
@FXML
private TableView<SimpleStringProperty> table;
@FXML
private TableColumn<SimpleStringProperty, String> data;
@FXML
private void initialize()
{
this.data.setCellValueFactory(cellData -> cellData.getValue());
this.data.setCellFactory(event -> new EditCell(this.observablePrnPropertyData, this.table));
}
public void display(final PrnProperty prnProperty)
{
this.observablePrnPropertyData = PrnPropertyUtil.getObservableDataFromPrnProperty(prnProperty);
this.table.setItems(this.observablePrnPropertyData);
}
private final class EditCell extends TableCell<SimpleStringProperty, String>
{
@Override
public void updateItem(String item, boolean empty)
{
super.updateItem(item, empty);
if (empty)
{
this.setText(null);
this.setGraphic(null);
}
else
{
this.setUpContextMenu();
this.setText(this.getString());
this.setGraphic(null);
}
}
private void setUpContextMenu()
{
// Context menu
ContextMenu contextMenu = new ContextMenu();
// context menu Move up
this.moveUp = new MenuItem("Move up");
this.moveUp.setOnAction(event -> this.moveUp(this.table, this.observablePrnPropertyData));
contextMenu.getItems().add(this.moveUp);
// Context menu for move down
this.moveDown = new MenuItem("Move down");
this.moveDown.setOnAction(event -> this.moveDown(this.table, this.observablePrnPropertyData));
contextMenu.getItems().add(this.moveDown);
// Add context menu
this.setContextMenu(contextMenu);
}
public void moveUp(final TableView<?> table, ObservableList listToManipulate)
{
final int selectedIndex = table.getSelectionModel().getSelectedIndex();
final Object removeItem = listToManipulate.remove(selectedIndex);
final int newIndex = selectedIndex - 1;
listToManipulate.add(newIndex, removeItem);
this.changeTableCellFocus(table, newIndex);
}
public void moveDown(final TableView<?> table, ObservableList listToManipulate)
{
final int selectedIndex = table.getSelectionModel().getSelectedIndex();
final Object remove = listToManipulate.remove(selectedIndex);
final int newIndex = selectedIndex + 1;
listToManipulate.add(newIndex, remove);
this.changeTableCellFocus(table, newIndex);
}
public void changeTableCellFocus(final TableView<?> table, final int focusIndex)
{
table.requestFocus();
table.getSelectionModel().clearAndSelect(focusIndex);
table.getFocusModel().focus(focusIndex);
}
}
}
如果有人能给出一个可行的例子,那就太好了。我真的很想知道我做错了什么。
【问题讨论】:
-
您能否提供更多有关如何创建表格的代码。这很重要,因为目前我无法从您的代码中判断您是要移动单个单元格还是整行。此外,数据绑定很重要,因此如果您在其他位置有它,也请添加该代码。
-
我对代码进行了一些更改以包含更多信息。
-
您的代码将移动整行,而不仅仅是一个单元格(尽管现在看起来您只有一列)。这是一个完整的 hack,但请尝试将对
changeTableCellFocus(...)的调用封装在Platform.runLater(...)中。 -
我已经尝试过
Platform.runLater(...),但我仍然遇到同样的问题。整行向上移动,但焦点不会更改到新行位置。 -
javafx-1 "= javafx script is notlevant" 在这里和所有其他 javafx 问题中!