我想为ListView实现自定义CellFactory:
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
public class MainApp extends Application
{
ListView<String> list = new ListView<String>();
ObservableList<String> data = FXCollections.observableArrayList(
"Option 1",
"Option 2",
"Option 3",
"Option 4",
"Option 5"
);
@Override
public void start(Stage stage)
{
VBox box = new VBox();
Scene scene = new Scene(box, 200, 200);
stage.setScene(scene);
stage.setTitle("ListViewSample");
box.getChildren().addAll(list);
VBox.setVgrow(list, Priority.ALWAYS);
list.setItems(data);
list.setCellFactory(new Callback<ListView<String>, ListCell<String>>()
{
@Override
public ListCell<String> call(ListView<String> list)
{
return new ColorRectCell();
}
}
);
stage.show();
}
class ColorRectCell extends ListCell<String>
{
public ColorRectCell()
{
addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent mouseEvent)
{
if (mouseEvent.getButton().equals(MouseButton.PRIMARY) && !isEmpty())
{
if (mouseEvent.getClickCount() == 2)
{
System.out.println(">>>>>>>>> Clicked");
}
}
}
});
}
@Override
public void updateItem(String item, boolean empty)
{
super.updateItem(item, empty);
if (item != null)
{
setText(item);
}
}
}
public static void main(String[] args)
{
launch(args);
}
}
我想激活双击监听器,只有当我点击带有文本的行时,如果行是空的则跳过它。将双击监听器实现到CellFactory的正确方法是什么?