仅通过左键单击选择ListView项目

时间:2015-02-24 21:28:46

标签: java javafx

使用JavaFX ListView时,如果右键单击项目,则会选择该项目。

如果左键单击,是否可以选择项目?

2 个答案:

答案 0 :(得分:2)

只需过滤MOUSE_PRESSED事件,检查辅助按钮是否已关闭,使用它并在需要时添加自定义处理代码。

右键单击也可以在OS X触控板上触发ContextMenuEvent.CONTEXT_MENU_REQUESTED事件(此类事件有点奇怪,会触发选择),因此也会过滤并使用这些事件。

这对我有用:

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

答案 1 :(得分:1)

可能这可以帮助

-Controller

@FXML
ListView<String> listT=new ListView<String>();
@FXML
Label lbl=new Label();

public void initialize(URL location, ResourceBundle resources) {
     listT=new Listv(listT);

} 

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