1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| package listview.context;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SplitPane;
import javafx.stage.Stage;
import java.util.stream.IntStream;
public final class Main extends Application {
public static void main(final String... args) {
launch(args);
}
@Override
public void start(final Stage primaryStage) throws Exception {
selectionProperty().addListener((observable, oldValue, newValue) -> {
System.out.printf("Selection: %s -> %s%n", oldValue, newValue);
});
final int columns = 5;
final int rows = 5;
final var root = new SplitPane();
IntStream.range(0, columns)
.mapToObj(column -> {
final var listView = new ListView<String>();
IntStream.range(0, rows)
.mapToObj(row -> String.format("%d - %d", row, column))
.forEach(listView.getItems()::add);
listView.setCellFactory(list -> new ListCell<>() {
private final ContextMenu contextMenu = new ContextMenu();
{
final var selectItem = new MenuItem("Select");
selectItem.setOnAction(event -> selection.set(getItem()));
contextMenu.getItems().add(selectItem);
}
@Override
protected void updateItem(String value, boolean empty) {
super.updateItem(value, empty);
final var String = value;
setText(value);
final var contextMenu = empty ? null : this.contextMenu;
setContextMenu(contextMenu);
}
});
return listView;
})
.forEach(root.getItems()::add);
final var scene = new Scene(root);
primaryStage.setWidth(800);
primaryStage.setHeight(600);
primaryStage.setScene(scene);
primaryStage.show();
Platform.runLater(() -> {
final double dx = 1.0 / columns;
final var dividerPositions = IntStream.range(0, columns - 1)
.mapToDouble(index -> (index + 1) * dx)
.toArray();
root.setDividerPositions(dividerPositions);
});
}
private final ReadOnlyStringWrapper selection = new ReadOnlyStringWrapper(this, "selection", null);
public final String getSelection() {
return selection.get();
}
private final ReadOnlyStringProperty selectionProperty() {
return selection.getReadOnlyProperty();
}
} |
Partager