logo
down
shadow

JavaFx property binding with multiple objects on on screen


JavaFx property binding with multiple objects on on screen

Content Index :

JavaFx property binding with multiple objects on on screen
Tag : javafx , By : Webtoad
Date : November 29 2020, 04:01 AM

it helps some times This looks like a perfect time to use a ListView with custom ListCell implementations.
The sample application below shows a very basic application that displays each Person object in a ListView. We will provide our own ListCell so we can control exactly how each Person gets displayed.
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.Separator;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;

public class ListViewDetailSample extends Application {

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

    @Override
    public void start(Stage primaryStage) {

        // Simple interface
        VBox root = new VBox(5);
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.CENTER);

        // First, let's create our list of Persons
        ObservableList<Person> persons = FXCollections.observableArrayList();
        persons.addAll(
                new Person("John", 34),
                new Person("Cheyenne", 24),
                new Person("Micah", 17),
                new Person("Katelyn", 28)
        );

        // Create a ListView
        ListView<Person> listView = new ListView<>();

        // Bind our list to the ListView
        listView.setItems(persons);

        // Now, for the magic. We'll create our own ListCells for the ListView. This allows us to create a custom
        // layout for each individual cell. For this sample, we'll include a profile picture, the name, and the age.
        listView.setCellFactory(new Callback<ListView<Person>, ListCell<Person>>() {
            @Override
            public ListCell<Person> call(ListView<Person> param) {
                return new ListCell<Person>() {
                    @Override
                    protected void updateItem(Person person, boolean empty) {
                        super.updateItem(person, empty);

                        // Set any empty cells to show nothing
                        if (person == null || empty) {
                            setText(null);
                            setGraphic(null);
                        } else {
                            // Here we can build our layout. We'll use a HBox for our root container
                            HBox cellRoot = new HBox(5);
                            cellRoot.setAlignment(Pos.CENTER_LEFT);
                            cellRoot.setPadding(new Insets(5));

                            // Add our profile picture
                            ImageView imgProfilePic = new ImageView("/sample/user.png");
                            imgProfilePic.setFitHeight(24);
                            imgProfilePic.setFitWidth(24);
                            cellRoot.getChildren().add(imgProfilePic);

                            // A simple Separator between the photo and the details
                            cellRoot.getChildren().add(new Separator(Orientation.VERTICAL));

                            // Now, create a VBox to hold the name and age
                            VBox vBox = new VBox(5);
                            vBox.setAlignment(Pos.CENTER_LEFT);
                            vBox.setPadding(new Insets(5));

                            // Add our Person details
                            vBox.getChildren().addAll(
                                    new Label("Name: " + person.getName()),
                                    new Label("Age: " + person.getAge())
                            );

                            // Add our VBox to the cellRoot
                            cellRoot.getChildren().add(vBox);

                            // Finally, set this cell to display our custom layout
                            setGraphic(cellRoot);
                        }
                    }
                };
            }
        });

        // Now, add our ListView to the root layout
        root.getChildren().add(listView);

        // Show the Stage
        primaryStage.setWidth(450);
        primaryStage.setHeight(400);
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
}

// Simple Person class
class Person {

    private final StringProperty name = new SimpleStringProperty();
    private final IntegerProperty age = new SimpleIntegerProperty();

    public Person(String name, int age) {
        this.name.set(name);
        this.age.set(age);
    }

    public String getName() {
        return name.get();
    }

    public StringProperty nameProperty() {
        return name;
    }

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

    public int getAge() {
        return age.get();
    }

    public IntegerProperty ageProperty() {
        return age;
    }

    public void setAge(int age) {
        this.age.set(age);
    }
}
    // Create a list to hold our individual Person displays
    ObservableList<Node> personDisplays = FXCollections.observableArrayList();

    // Now add a new PersonDisplay to the list for each Person in the personsList
    persons.forEach(person -> personDisplays.add(new PersonDisplay(person)));

    // Bind our personsDisplay list to the children of our root VBox
    Bindings.bindContent(root.getChildren(), personDisplays);
class PersonDisplay extends HBox {

    public PersonDisplay(Person person) {
        // First, let's configure our root layout
        setSpacing(5);
        setAlignment(Pos.CENTER_LEFT);
        setPadding(new Insets(5));

        // Add our profile picture
        ImageView imgProfilePic = new ImageView("/user.png");
        imgProfilePic.setFitHeight(24);
        imgProfilePic.setFitWidth(24);
        getChildren().add(imgProfilePic);

        // A simple Separator between the photo and the details
        getChildren().add(new Separator(Orientation.VERTICAL));

        // Now, create a VBox to hold the name and age
        VBox vBox = new VBox(5);
        vBox.setAlignment(Pos.CENTER_LEFT);
        vBox.setPadding(new Insets(5));

        // Add our Person details
        vBox.getChildren().addAll(
                new Label("Name: " + person.getName()),
                new Label("Age: " + person.getAge())
        );

        // Add our VBox to the layout
        getChildren().add(vBox);
    }
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

binding bean property with multiple objects in struts


Tag : jsp , By : user181945
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Yes. Name all your select boxes the same way (foos, for example), and have a method
public void setFoos(String[] foos) {
    ...
}

Are JavaFX Property objects threadsafe for multiple asynchronous writes?


Tag : java , By : Bimal Poudel
Date : March 29 2020, 07:55 AM
should help you out SimpleObjectProperty is not thread safe.
You see this in the source: javafx/beans/property/ObjectPropertyBase.set is not synchronized, or you use a tool like http://vmlens.com witch looks for you:-)

WPF binding to the same property of multiple objects in a collection


Tag : chash , By : David B
Date : March 29 2020, 07:55 AM
Does that help It seems to me that object encapsulation would really help you here, rather than trying to make MultiBinding do something it's not really equipped to handle.
So, without seeing your code, I'll make a couple of assumptions:
string Name { get; set; }
string ElementType { get; set; }
string SelectionProfile { get; set; }
string Material { get; set; }
... etc
// Represents a list of selected items
ObjectSelectionViewModel SelectedItems { get; }
public class ObjectSelectionViewModel : ObjectViewModel
{
    // The current list of selected items.
    public ObservableCollection<ObjectViewModel> SelectedItems { get; }

    public ObjectSelectionViewModel()
    {
        SelectedItems = new ObservableCollection<ObjectViewModel>();
        SelectedItems.CollectionChanged += (o, e) =>
        {
             // Pseudo-code here
             if (items were added)
             {
                  // Subscribe each to PropertyChanged, using Item_PropertyChanged
             }
             if (items were removed)
             {
                 // Unsubscribe each from PropertyChanged
             }                   
        };
    }

    void Item_PropertyChanged(object sender, NotifyPropertyChangedArgs e)
    {
         // Notify that the local, group property (may have) changed.
         NotifyPropertyChanged(e.PropertyName);
    }

    public override string Name
    {
        get 
        {
            if (SelectedItems.Count == 0)
            {
                 return "[None]";
            }
            if (SelectedItems.IsSameValue(i => i.Name))
            {
                 return SelectedItems[0].Name;
            }
            return string.Empty;
        }
        set
        {
            if (SelectedItems.Count == 1)
            {
                SelectedItems[0].Name = value;
            }
            // NotifyPropertyChanged for the traditional MVVM ViewModel pattern.
            NotifyPropertyChanged("Name");
        }           
    }

    public override string SelectionProfile
    {
        get 
        {
            if (SelectedItems.Count == 0)
            {
                 return "[None]";
            }
            if (SelectedItems.IsSameValue(i => i.SelectionProfile)) 
            {
                return SelectedItems[0].SelectionProfile;
            }
            return "[Multi]";
        }
        set
        {
            foreach (var item in SelectedItems)
            {
                item.SelectionProfile = value;
            }
            // NotifyPropertyChanged for the traditional MVVM ViewModel pattern.
            NotifyPropertyChanged("SelectionProfile");
        }           
    }

    ... etc ...
}

// Extension method for IEnumerable
public static bool IsSameValue<T, U>(this IEnumerable<T> list, Func<T, U> selector) 
{
    return list.Select(selector).Distinct().Count() == 1;
}

Binding Label property to Image property using javafx concurrency Task<Void>


Tag : java , By : Sebastian Gift
Date : March 29 2020, 07:55 AM
wish of those help The error is that you can not bind a ReadOnlyStringProperty to an ObjectProperty.
You should add a change listener (docs) to the task message property (docs) and create an image which you then apply to your image view:
public void monitor() {
    task1 = new Task<Void>() {
        @Override
        protected Void call() {
            System.out.println("run called");
            int i = 1;
            while (true) {
                try {
                    Thread.sleep(1000);
                    updateMessage(i + ".png");
                    System.out.println("i: " + i);
                } catch (Exception e) {

                }
                i++;
            }
        }
    };
    task1.messageProperty().addListener((observable, oldValue, newValue) -> {
        System.out.println(newValue);
        Image image = new Image(getClass().getResourceAsStream("images/" + newValue));
        imv.setImage(image);
    });
}

javafx binding from list property to arbitrary object property


Tag : javafx , By : Menno
Date : March 29 2020, 07:55 AM
this one helps. I am trying to get a class to have a property bound to another class's list property, where the 1st property is derived from a summarizing calculation over the objects in the list. The code below is a simplified version of my production code. (The production code is doing a summary over DateTime objects -- the essential part of the code below is the binding between a list and an object property (here, it is a String for simplicity).) , Keep in mind that I made this answer based on your minimal example:
class Thing(x: Int) {
    val xProperty = SimpleIntegerProperty(x)
    var x by xProperty

    val yProperty = SimpleStringProperty("xyz")
    var y by yProperty
}


class MainView : View() {
    val things = FXCollections.observableList(mutableListOf<Thing>()) {
        arrayOf<Observable>(it.xProperty)
    }

    val thingsProperty = SimpleListProperty<Thing>(things)

    val totalBinding = integerBinding(listProperty) {
        value.map { it.x }.fold(0, { total, next -> total + next })
    }

    val phraseBinding = stringBinding(totalBinding) { "There are $value things." }

    override val root = vbox {
        label(phraseBinding)
        button("Add Thing") {
            action {
                list.add(Thing(5))
            }
        }
    }
}
Related Posts Related QUESTIONS :
  • javafx trigger calculation across classes with bindings
  • Animation not working on FXMLController
  • How do I add a Tooltip to a rectangular region of a JavaFX Canvas
  • JavaFX : Highlight VBox on mouse click and change color when unfocused
  • Binding an enum's toString() to a Label
  • TextField in PopOver with strange behavior
  • JavaFX: Resizing Panes when resizing window
  • Deleting multiple rows from TableView
  • FXML: An elegant way to bind a child width/height to the parent's width/height
  • Is it possible don't close popup in DatePicker on select date event
  • How to render a Scene in JavaFX? (2D Game)
  • How do I call a method from hovering in FXML?
  • How can I animate the height property of a rectangle object?
  • why this code doesn't produce a tab pane?
  • How to corectly obtain the outer bounds of a node in JavaFX
  • Accessing the Value of a CheckBox in TableView
  • How to add image in a button?
  • Updating two text objects in JavaFX, one field after another, only seeing final result of both changes
  • JavaFX : How to manage the z-index of stages
  • How to display day from selected date using javafx?
  • How can I bind a Label's textFillProperty?
  • derby database open and close connections
  • How to serialize a map that contains Image objects?
  • Creating Custom Control in Jar for Gluon Scene Builder 11.00
  • How to update or change table raw's values in javafx without making the table editable?
  • How can I display all rows of a count query in a javafx textarea? It is only diplaying the first row instead of two rows
  • How to write a function to return a javafx stage
  • How to change textfield inputs to only numbers in javafx?
  • JavaFX: how to read CurrentTime of MediaPlayer while not in JavaFX App Thread
  • Add JavaFX Label - (Using Only Java / JavaFX Code) - To Existing GUI Created With Scenebuilder / FXML
  • JavaFx: about quartz scheduler
  • NullPointerException passing a string from a window to another
  • How to add regex to textfieldtablecell?
  • How to set font for label in JavaFx from root folder?
  • JavaFX 8 count rows in "textarea"
  • Why does prefWidth in javafx takes an argument called height?
  • TreeView scrolling jumps when using large graphic nodes (TornadoFX/JavaFX)
  • Binding LongProperty to internal changes of ListProperty
  • Can't add ImageView to background JavaFX - No fxml
  • Using setStyle to change background color in JavaFx
  • javafx line chart spread out categories along gridlines
  • How to get Key Press working on two file Javafx project
  • fxml: How to handle button action in the controller?
  • Graphic of ButtonCell ComboBox
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com