Reputation: 18149
When using a JavaFX ListView, if you right-click an item, the item is selected.
Is it possible to only select an item if you left-click it?
Upvotes: 2
Views: 1271
Reputation: 18415
Just filter the MOUSE_PRESSED event, check if the secondary button is down, consume it and add your custom handling code if you need one.
A right-click can also trigger a ContextMenuEvent.CONTEXT_MENU_REQUESTED
event on an OS X touchpad (and such events will, somewhat weirdly, trigger a selection) so also filter and consume these events.
This works for me:
public class ListViewSample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("List View Sample");
ListView<String> list = new ListView<String>();
ObservableList<String> items =FXCollections.observableArrayList ( "Single", "Double", "Suite", "Family App");
list.setItems(items);
// filter right mouse button
list.addEventFilter(MouseEvent.MOUSE_PRESSED, e ->
{
if( e.isSecondaryButtonDown()) {
e.consume();
}
});
list.addEventFilter(ContextMenuEvent.CONTEXT_MENU_REQUESTED, Event::consume);
// verify selection via logging
list.getSelectionModel().selectedItemProperty().addListener(
(ChangeListener<String>) (observable, oldValue, newValue) -> System.out.println( "Item selected: " + observable + ", " + oldValue + ", " + newValue)
);
StackPane root = new StackPane();
root.getChildren().add(list);
primaryStage.setScene(new Scene(root, 200, 250));
primaryStage.show();
}
}
Upvotes: 3
Reputation: 1121
may be this can help
-Controller
@FXML
ListView<String> listT=new ListView<String>();
@FXML
Label lbl=new Label();
public void initialize(URL location, ResourceBundle resources) {
listT=new Listv(listT);
}
class extending listview
public class Listv extends ListView<String>{
ListView<String> llist=new ListView<String>();
int PrevIndex=0;
public Listv(ListView<String> l) {
this.llist=l;
llist.getItems().add("A");
llist.getItems().add("A");
llist.getItems().add("A");
llist.getItems().add("A");
this.llist.setOnMouseClicked(listclicked);
this.llist.getSelectionModel().selectedIndexProperty().addListener(indexChanged);
}
EventHandler<MouseEvent> listclicked=new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if( event.getButton() == MouseButton.SECONDARY)
{
Platform.runLater(()->{
llist.getSelectionModel().select(PrevIndex);
});
}
}
};
ChangeListener<Object> indexChanged=new ChangeListener<Object>() {
@Override
public void changed(ObservableValue<? extends Object> observable,Object oldValue, Object newValue) {
PrevIndex=Integer.parseInt(oldValue.toString());
}
};
}
Upvotes: 1