我想在JavaFX 8中监听表格视图的选择更改。如果我将ChangeListener添加到MultipleSelectionModel的selectedItemProperty(或selectedIndexProperty),则在以下情况下不会触发:
多个行已经被选中,现在我选择了一个新的单行。如果这行是之前选择的最后一行,则不会有反应。这是因为selectedItemProperty仅包含一个项目而不是所有已选项目的列表。但不幸的是,没有selectedItemsProperty,这很奇怪,因为方法getSelectedItems()存在。我不知道在哪里添加侦听器才能使它在任何情况下都起作用。
以下是示例代码:
请注意,此示例中的ListView仅用于视觉目的。
以下是示例代码:
import java.util.stream.Collectors;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class MultipleSelectionTest extends Application
{
private ListView<Integer> list = new ListView<>();
private TableView<String> table = new TableView<>();
private TableColumn<String, String> column1 = new TableColumn<>("Numbers");
@Override
public void start(Stage primaryStage) throws Exception
{
HBox box = new HBox(list, table);
primaryStage.setScene(new Scene(box, 300, 500));
initializeTable();
initializeList();
primaryStage.show();
}
private void initializeTable()
{
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
table.getColumns().add(column1);
column1.setCellValueFactory(s -> new SimpleStringProperty(s.getValue()));
table.setItems(FXCollections.observableArrayList("One", "Two", "Three", "Four", "Five", "Six", "Seven"));
}
private void initializeList()
{
table.getSelectionModel().selectedItemProperty().addListener((property, oldValue, newValue) ->
{
ObservableList<Integer> convertedItems = FXCollections.observableList(
table.getSelectionModel().getSelectedItems()
.stream()
.map(this::convertNumber)
.collect(Collectors.toList()));
list.setItems(convertedItems);
});
}
private int convertNumber(String expression)
{
switch (expression)
{
case "One": return 1;
case "Two": return 2;
case "Three": return 3;
case "Four": return 4;
case "Five": return 5;
case "Six": return 6;
case "Seven": return 7;
default: throw new IllegalArgumentException();
}
}
public static void main(String[] args)
{
launch();
}
}
请注意,此示例中的ListView仅用于视觉目的。