Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

listview - Add text from Arraylist to TextArea javafx

I wonder how to do to get various attributes from my objects stored in an ArrayList to my TextArea? I have an ListView and depending on which of the lines in the ListView you press, different text should appear in the TextArea. I just can't get it to work.

Here is a bit of my code this far. Animals is another class.

    ListView<String> cats = new ListView<>();
    cats.setPrefSize(90, 200);
    cats.getItems().addAll(
            "First cat",
            "Second cat" 
    );

    final ArrayList<Animals> catsdesricption = new ArrayList<Animals>();
    Animals FirstCat = new Animals("First cat", "cats", "is small and fluffy");

    catsdesricption.add(FirstCat);
    TextArea description = new TextArea();
    description.setMaxSize(300, 200);
    description.setWrapText(true);

    VBox vbox = new VBox();
    Label heading = new Label("Cats");
    heading.setFont(new Font("Times new Roman", 20));

    HBox layout = new HBox();

    layout.getChildren().addAll(cats, catsdesricption);
    vbox.getChildren().addAll(heading, layout);

    Scene scene = new Scene(vbox, 420, 250);
    primaryStage.setScene(scene);
    primaryStage.show();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After taking a closer look at your code, I noticed a ton of problems. To answer your original question. You need a listener on the SelectionModel's ItemProperty to updated the TextArea.

    cats.getSelectionModel().selectedItemProperty().addListener((obs, oldAnimal, newAnimal) -> {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("Name: ").append(newAnimal.getName()).append(System.lineSeparator());
        stringBuilder.append("Type: ").append(newAnimal.getType()).append(System.lineSeparator());
        stringBuilder.append("About: ").append(newAnimal.getAbout()).append(System.lineSeparator());        

        description.setText(stringBuilder.toString());
    });

First problem:

ListView<String> cats = new ListView<>();
cats.setPrefSize(90, 200);
cats.getItems().addAll(
        "First cat",
        "Second cat" 
);

It appears you want the ListView to hold Animal objects, but you are using String objects.

The Fix

ListView<Animal> cats = new ListView<>();
cats.getItems().add(new Animal("First cat", "cats", "is small and fluffy"));
cats.getItems().add(new Animal("Second cat", "cats", "is big and fluffy"));

Second Problem: Now that the ListView is handling Animal objects, we need to use the ListView's CellFActory to tell the ListView what text to display. In this case, the name will be displayed.

    cats.setCellFactory((ListView<Animal> param) -> {
        ListCell<Animal> cell = new ListCell<Animal>() {                
            @Override
            protected void updateItem(Animal item, boolean empty) {
                super.updateItem(item, empty);
                if (item != null) {
                    setText(item.getName());
                } else {
                    setText("");
                }
            }
        };

        return cell;
    }); 

Now that these two things are done, the original question code can be added. The code above that changes the TextArea's text depending on which item is selected in the ListView.

Full Code:

Main

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.control.ListCell;
    import javafx.scene.control.ListView;
    import javafx.scene.control.TextArea;
    import javafx.scene.layout.HBox;
    import javafx.scene.layout.VBox;
    import javafx.scene.text.Font;
    import javafx.stage.Stage;

    /**
     * JavaFX App
     */
    public class App extends Application {

        @Override
        public void start(Stage primaryStage) {
            ListView<Animal> cats = new ListView<>();
            cats.getItems().add(new Animal("First cat", "cats", "is small and fluffy"));
            cats.getItems().add(new Animal("Second cat", "cats", "is big and fluffy"));

            cats.setCellFactory((ListView<Animal> param) -> {
                ListCell<Animal> cell = new ListCell<Animal>() {                
                    @Override
                    protected void updateItem(Animal item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            setText(item.getName());
                        } else {
                            setText("");
                        }
                    }
                };

                return cell;
            }); 
            cats.setPrefSize(90, 200);           

            TextArea description = new TextArea();
            description.setMaxSize(300, 200);
            description.setWrapText(true);

            cats.getSelectionModel().selectedItemProperty().addListener((obs, oldAnimal, newAnimal) -> {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("Name: ").append(newAnimal.getName()).append(System.lineSeparator());
                stringBuilder.append("Type: ").append(newAnimal.getType()).append(System.lineSeparator());
                stringBuilder.append("About: ").append(newAnimal.getAbout()).append(System.lineSeparator());        

                description.setText(stringBuilder.toString());
            });

            VBox vbox = new VBox();
            Label heading = new Label("Cats");
            heading.setFont(new Font("Times new Roman", 20));

            HBox layout = new HBox(cats, description);

            vbox.getChildren().addAll(heading, layout);

            Scene scene = new Scene(vbox, 420, 250);
            primaryStage.setScene(scene);
            primaryStage.show();
        }

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

My Animal Class: (You did not post yours)

/**
 *
 * @author blj0011
 */
class Animal {
    private String name;
    private String type;
    private String about;

    public Animal(String name, String type, String about) {
        this.name = name;
        this.type = type;
        this.about = about;
    }

    public String getAbout() {
        return about;
    }

    public void setAbout(String about) {
        this.about = about;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Animals{name=").append(name);
        sb.append(", type=").append(type);
        sb.append(", about=").append(about);
        sb.append('}');
        return sb.toString();
    }    
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...