用TextField替换选定的Label

时间:2015-03-23 17:38:28

标签: java listview javafx-2 javafx-8

我使用以下内容创建了ListView Label

ListView<Label> list = new ListView<Label>();
Image folder = new Image(getClass().getResourceAsStream("folder.png"));
ObservableList<Label> data = FXCollections.observableArrayList();   
for (int i = 0; i < 6; i++) {
    Label lbl = new Label();
    lbl.setText("label" + i);
    lbl.setGraphic(new ImageView(folder));
    lbl.setContentDisplay(ContentDisplay.LEFT); 
    lbl.setGraphicTextGap(10.2); 
    data.add(lbl);              
}
list.setItems(data);

我希望用户能够双击Label中的任意ListView,所选Label应替换为TextField,以便用户可以动态输入新的标签名称。

用户按 Enter 后,TextField应转回Label

1 个答案:

答案 0 :(得分:1)

不要将Label用作ListView数据的类型。使用String。然后,您可以使用具有您描述的功能的标准TextFieldListCell。由于您需要标准单元格显示中的图形,因此只需子类TextFieldListCell并覆盖相应的方法,以便在未显示文本字段时包含图形:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListView;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import javafx.util.converter.DefaultStringConverter;

public class EditableListViewTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        ListView<String> list = new ListView<>();
        Image testImg = new Rectangle(12, 12, Color.CORNFLOWERBLUE).snapshot(null, null);
        for (int i = 0; i < 6; i++) {
            list.getItems().add("label "+i);
        }

        StringConverter<String> identityStringConverter = new DefaultStringConverter();

        list.setCellFactory(lv -> new TextFieldListCell<String>(identityStringConverter) {

            private ImageView imageView = new ImageView(testImg);


            @Override
            public void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (! empty && ! isEditing()) {
                    setStaticGraphic();
                }
            }

            @Override
            public void cancelEdit() {
                super.cancelEdit();
                setStaticGraphic();
            }

            @Override
            public void commitEdit(String newValue) {
                super.commitEdit(newValue);
                setStaticGraphic();
            }

            private void setStaticGraphic() {
                setGraphic(imageView);
                setContentDisplay(ContentDisplay.LEFT);
                setGraphicTextGap(10.2);                
            }
        });

        list.setEditable(true);

        primaryStage.setScene(new Scene(new BorderPane(list), 250, 400));
        primaryStage.show();
    }

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