IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaFX Discussion :

Binding d'une TableView éditable avec mon modèle


Sujet :

JavaFX

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Nouveau candidat au Club
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2012
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Juin 2012
    Messages : 1
    Par défaut Binding d'une TableView éditable avec mon modèle
    Bonjour,

    J'aimerais faire une TableView éditable. J'ai une table avec 3 colonnes qui représente une liste d'accessoires. Il y a une colonne pour l'intitulé de l'accessoire, une pour le prix et une pour les actions.

    J'ai fait un bind bidirectionnel sur la liste mais les objets de cette liste proviennent du modèle et ne sont donc pas de type observable (plutôt String et Long Java).

    Y aurait-il une solution propre pour que le contenu de ces objets soit lui aussi bindé entre mon modèle et la View. J'essaie de trouver une solution réutilisable facilement pour d'autres objets de mon modèle. C'est pour cela que si possible, j'évite de recréer une classe spécifique à mon accessoire.

    J'avais imaginé utiliser la classe JavaBeanObjectPropertyBuilder mais elle ne semble pas répondre à mes besoins vue que je m'intéresse à tous les champs de mon objet Accessoire.

    Merci pour votre aide...

  2. #2
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 900
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 48
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 900
    Billets dans le blog
    54
    Par défaut
    Bon c'est pas mon domaine de prédilection donc je vais probablement dire des grosses c*ies mais tu dois pouvoir te créer une classe générique en explorant, via la reflection, les setters et getters de ton beans (en listant toutes les methodes getXXX, isXXX et setXXX) ou en parcourant son BeanInfo (s'il y en a un) pour faire un truc qui puisse générer m'importe quelle propriété.


    On peut rapidement faire un truc "simple" du genre de ce qui suit, même si je ne suis pas sur que ça réponde entièrement a ta question :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    package test;
     
    import java.lang.reflect.Method;
    import javafx.beans.property.ObjectProperty;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
     
    public class ObservableBeanAdapter<B, T> {
     
        private B bean;
        private String property;
     
        /**
         * Creates a new instance.
         * @param bean The bean.
         * @param property The property to access.
         */
        public ObservableBeanAdapter(B bean, String property) {
            this.bean = bean;
            this.property = property;
            populateValue();
            valueProperty().addListener(valueChangeListener);
        }
        /**
         * The observable property.
         */
        private final ObjectProperty<T> value = new SimpleObjectProperty<>(this, "value", null);
     
        public final void setValue(T propertyValue) {
            value.set(propertyValue);
        }
     
        public final T getValue() {
            return value.get();
        }
     
        public final ObjectProperty<T> valueProperty() {
            return value;
        }
     
        /**
         * Set initial value in the observable property by calling the appropriate getter in the underlying bean.
         */
        private void populateValue() {
            T propertyValue = null;
            try {
                String methodName = "get" + property.substring(0, 1).toUpperCase() + property.substring(1, property.length());
                propertyValue = executeMethod(bean, methodName, null);
            } catch (Exception e1) {
    //            e1.printStackTrace();
                // Now look for boolean getter instead.
                try {
                    String methodName = "is" + property.substring(0, 1).toUpperCase() + property.substring(1, property.length());
                    propertyValue = executeMethod(bean, methodName, null);
                } catch (Exception e2) {
    //                e2.printStackTrace();
                }
            }
            setValue(propertyValue);
        }
        /**
         * Called whenever the value changes.
         * <br/>Calls the setter in the underlying bean.
         */
        private final ChangeListener<T> valueChangeListener = new ChangeListener<T>() {
     
            @Override
            public void changed(ObservableValue<? extends T> observableValue, T oldValue, T newValue) {
                try {
                    String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1, property.length());
                    executeMethod(bean, methodName, newValue);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
     
        /**
         * Execute a method on the bean.
         * @param bean The bean.
         * @param methodName The name of the method
         * @param arg Argument of the method:
         * <ul>
         * <li>{@code Null} when calling the getter.</li>
         * <li>The new value when calling the setter.</li>
         * </ul>
         * @return
         * @throws Exception 
         */
        private T executeMethod(B bean, String methodName, Object arg) throws Exception {
            Class argType = (arg == null) ? null : arg.getClass();
            T result = null;
            try {
                result = executeMethodForArgType(bean, methodName, argType, arg);
            } catch (NoSuchMethodException nsme) {
                // We only deal with the setter as the getter does not take any argument.
                if (argType != null) {
    //                nsme.printStackTrace();
                    // For number classes try with literal classes instead.
                    if (argType == Boolean.class) {
                        result = executeMethodForArgType(bean, methodName, boolean.class, arg);
                    } else if (argType == Byte.class) {
                        result = executeMethodForArgType(bean, methodName, byte.class, arg);
                    } else if (argType == Character.class) {
                        result = executeMethodForArgType(bean, methodName, char.class, arg);
                    } else if (argType == Short.class) {
                        result = executeMethodForArgType(bean, methodName, short.class, arg);
                    } else if (argType == Integer.class) {
                        result = executeMethodForArgType(bean, methodName, int.class, arg);
                    } else if (argType == Long.class) {
                        result = executeMethodForArgType(bean, methodName, long.class, arg);
                    } else if (argType == Float.class) {
                        result = executeMethodForArgType(bean, methodName, float.class, arg);
                    } else if (argType == Double.class) {
                        result = executeMethodForArgType(bean, methodName, double.class, arg);
                    } // For other types, will try all known public parent classes and interfaces types.
                    else {
                        Class[] parents = argType.getClasses();
                        int errors = 0;
                        for (Class parentClass : parents) {
                            try {
                                result = executeMethodForArgType(bean, methodName, parentClass, arg);
                                break;
                            } catch (NoSuchMethodException nsme1) {
                                nsme.addSuppressed(nsme1);
                            }
                        }
                        // Still could not find the parent, rethrow the error.
                        if (errors == parents.length) {
                            throw nsme;
                        }
                    }
                } else {
                    throw nsme;
                }
            }
            return result;
        }
     
        private T executeMethodForArgType(B bean, String methodName, Class argType, Object arg) throws Exception {
            Class<B> bClass = (Class<B>) bean.getClass();
            Method method = null;
            T result = null;
            // No argument: the getter.
            if (argType == null) {
                method = bClass.getMethod(methodName);
                Object methodResult = method.invoke(bean);
                result = (T) methodResult;
            } // Argument: the setter.
            else {
                method = bClass.getMethod(methodName, argType);
                Object methodResult = method.invoke(bean, arg);
                result = (T) methodResult;
            }
            return result;
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    package test;
     
    /**
     *
     * @author fabriceb
     */
    public class StupidBean {
     
        private boolean booleanValue = false;
        private int intValue = 0;
        private float floatValue = 0f;
        private String stringValue = "Hello World!";
     
        public boolean isBooleanValue() {
            return booleanValue;
        }
     
        public void setBooleanValue(boolean booleanValue) {
            this.booleanValue = booleanValue;
        }
     
        public float getFloatValue() {
            return floatValue;
        }
     
        public void setFloatValue(float floatValue) {
            this.floatValue = floatValue;
        }
     
        public int getIntValue() {
            return intValue;
        }
     
        public void setIntValue(int intValue) {
            this.intValue = intValue;
        }
     
        public String getStringValue() {
            return stringValue;
        }
     
        public void setStringValue(String stringValue) {
            this.stringValue = stringValue;
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    package test;
     
    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.stage.Stage;
     
    /**
     *
     * @author fabriceb
     */
    public class Main extends Application {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            launch(args);
        }
     
        @Override
        public void start(Stage primaryStage) {
            StupidBean sb = new StupidBean();
            ObservableBeanAdapter<StupidBean, Boolean> booleanObv = new ObservableBeanAdapter<>(sb, "booleanValue");
            ObservableBeanAdapter<StupidBean, Integer> intObv = new ObservableBeanAdapter<>(sb, "intValue");
            ObservableBeanAdapter<StupidBean, Float> floatObv = new ObservableBeanAdapter<>(sb, "floatValue");
            ObservableBeanAdapter<StupidBean, String> stringObv = new ObservableBeanAdapter<>(sb, "stringValue");
            System.out.println(booleanObv.getValue());
            System.out.println(intObv.getValue());
            System.out.println(floatObv.getValue());
            System.out.println(stringObv.getValue());
            booleanObv.setValue(Boolean.TRUE);
            intObv.setValue(10);
            floatObv.setValue(3.14f);
            stringObv.setValue("I am the king of the world!");
            System.out.println(booleanObv.getValue() + "\t" + sb.isBooleanValue());
            System.out.println(intObv.getValue() + "\t" + sb.getIntValue());
            System.out.println(floatObv.getValue() + "\t" + sb.getFloatValue());
            System.out.println(stringObv.getValue() + "\t" + sb.getStringValue());
            Platform.exit();
        }
    }
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

Discussions similaires

  1. j'ai une erreur 1004 avec mon vba ?
    Par isodoro dans le forum Macros et VBA Excel
    Réponses: 2
    Dernier message: 06/03/2009, 10h13
  2. Une vue qui affiche mon modèle entier ?
    Par igala.net dans le forum OpenGL
    Réponses: 7
    Dernier message: 18/07/2008, 17h02
  3. Comment faire avec mon modèle ?
    Par cyph3r dans le forum Schéma
    Réponses: 2
    Dernier message: 25/06/2008, 23h11
  4. Réponses: 2
    Dernier message: 04/09/2007, 13h53
  5. [MVC] Binding d'une proprieté 'societe' dans mon formulaire Utilisateur
    Par rlpg123 dans le forum Spring Web
    Réponses: 1
    Dernier message: 26/07/2006, 09h06

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo