JavaFX——ListView启用编辑状态

主要说一下ListView的可编辑状态的事件监听

FXML






<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.ergou.controller.ListViewController">
   <children>
      <ListView fx:id="listview" layoutX="33.0" layoutY="25.0" prefHeight="328.0" prefWidth="200.0" />
   children>
AnchorPane>

Controller

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.control.cell.TextFieldListCell;
import org.apache.log4j.Logger;
import java.net.URL;
import java.util.ResourceBundle;

public class ListViewController implements Initializable {

    private static Logger logger = Logger.getLogger(ListViewController.class);

    @FXML
    private ListView listview;

    private ObservableList<String> datalist = FXCollections.observableArrayList();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        listview.setItems(datalist);
        datalist.addAll("项目一", "项目二", "项目三");//设置列表要显示的数据
        listview.setCellFactory(TextFieldListCell.forListView());
        listview.setEditable(true);//设置列表可编辑
        listview.setOnEditStart(event -> {
            logger.info("开始编辑列表");
        });
        listview.setOnEditCommit(new EventHandler<ListView.EditEvent<String>>() {
            @Override
            public void handle(ListView.EditEvent<String> event) {
                logger.info("完成列表编辑");
                datalist.set(event.getIndex(), event.getNewValue());//修改列表编辑后的数据
            }
        });
    }
}

程序入口

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("/layout/listview.fxml"));
        primaryStage.setTitle("JavaFX");
        primaryStage.setScene(new Scene(root, 500, 400));
        primaryStage.show();
    }

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

你可能感兴趣的:(JavaFX)