2016-10-05 66 views
0

这个问题起初似乎很简单,但我已经有几天的麻烦了。检测鼠标点击选择可编辑组合框JavaFX

所以,我的问题是,我想检测鼠标点击和选择打开组合框选择时,并单击鼠标选择选项。

那么,什么是应该做的是检测在选择鼠标点击并同时获得所选择的价值,以及:

enter image description here

PS:我的组合框的代码可以在这里看到: Select JavaFX Editable Combobox text on click

随时提出其他问题。

回答

2

只需使用一个电池工厂,并注册与细胞的处理程序:

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.control.ComboBox; 
import javafx.scene.control.ListCell; 
import javafx.scene.layout.StackPane; 
import javafx.stage.Stage; 

public class ComboBoxMouseClickOnCell extends Application { 

    @Override 
    public void start(Stage primaryStage) { 
     ComboBox<String> combo = new ComboBox<>(); 
     combo.getItems().addAll("One", "Two", "Three"); 
     combo.setCellFactory(lv -> { 
      ListCell<String> cell = new ListCell<String>() { 
       @Override 
       protected void updateItem(String item, boolean empty) { 
        super.updateItem(item, empty); 
        setText(empty ? null : item); 
       } 
      }; 
      cell.setOnMousePressed(e -> { 
       if (! cell.isEmpty()) { 
        System.out.println("Click on "+cell.getItem()); 
       } 
      }); 
      return cell ; 
     }); 

     Scene scene = new Scene(new StackPane(combo), 300, 180); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    public static void main(String[] args) { 
     launch(args); 
    } 
} 
+0

我得到的Lambda表达式不会在该语言级别的错误的支持。 –

+0

@EerikMuuli然后配置您的IDE,以便使用Java 8,或将lambda表达式转换为类。 –

+0

谢谢!它非常完美! –