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

Composants Java Discussion :

[JSpinner] afficher et editer un nombre en hexadecimal


Sujet :

Composants Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre émérite
    Avatar de bpy1401
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2003
    Messages
    511
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 64
    Localisation : France, Eure (Haute Normandie)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2003
    Messages : 511
    Par défaut [JSpinner] afficher et editer un nombre en hexadecimal
    Bonjour,

    je souhaiterais avoir un spinner (style JSpinner) qui affiche le nombre en hexadécimal.

    Certain dirons que c'est hyper simple, moi je galère completement. j'ai regardé le site de sun sur les spinner, cherché dans cette liste, cela est resté sans succés

    Je pense qu'il faut passer par la méthode getEditor, mais je bute completement pour la modifier

    Qui peut m'aider
    merci
    Cordialement
    Page sur Developpez : http://pbriand.developpez.com

  2. #2
    Membre Expert
    Avatar de xavlours
    Inscrit en
    Février 2004
    Messages
    1 832
    Détails du profil
    Informations forums :
    Inscription : Février 2004
    Messages : 1 832
    Par défaut
    Bonjour,

    une solution (peut-être pas la meilleure, mais assez simple) est de définir une classe héritant de SpinnerNumberModel, qui redéfinisse les méthodes getValue, getNextValue et getPreviousValue pour renvoyer le nombre sous forme de String (et en hexadécimal) :
    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
    public class HexadecimalSpinnerNumberModel extends SpinnerNumberModel {
     
      public Object getValue() {
        Number value = (Number)super.getValue();
        return Integer.toHexString(value.intValue());
      }
     
      public Object getPreviousValue() {
        Number value = (Number)super.getPreviousValue();
        return Integer.toHexString(value.intValue());
      }
     
      public Object getNextValue() {
        Number value = (Number)super.getNextValue();
        return Integer.toHexString(value.intValue());
      }
    }
    Attention, ce Model ne renverra pas des nombres mais des strings. Pour la conversion, il faudra passer par parseInt et non par un cast.
    "Le bon ni le mauvais ne me feraient de peine si si si je savais que j'en aurais l'étrenne." B.V.
    Non au langage SMS ! Je ne répondrai pas aux questions techniques par MP.
    Eclipse : News, FAQ, Cours, Livres, Blogs.Et moi.

  3. #3
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 904
    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 904
    Billets dans le blog
    54
    Par défaut
    Le JSpinner me cause bien du soucis egalement. Sinon d'apres les sources son editeur repose sur un JFormattedTextField. Il est peut-etre donc possible de le hacker et de passer un NumberFormat appropie pour que l'editor affiche et accepte de l'hexadecimal.

    La methode du model me semble etre la plus simple a mettre en place cependant.
    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

  4. #4
    Membre émérite
    Avatar de bpy1401
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2003
    Messages
    511
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 64
    Localisation : France, Eure (Haute Normandie)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2003
    Messages : 511
    Par défaut
    Merci pour vos réponses, mais cela ne fonctionne pas.

    J'avais déjà essayer de définir une nouvelle classe héritant de SpinnerNumberModel mais j'obtiens le résultat suivant:

    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
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot format given Object as a Number
    	at java.text.DecimalFormat.format(DecimalFormat.java:480)
    	at java.text.Format.format(Format.java:133)
    	at javax.swing.text.InternationalFormatter.valueToString(InternationalFormatter.java:291)
    	at javax.swing.JFormattedTextField$AbstractFormatter.install(JFormattedTextField.java:925)
    	at javax.swing.text.DefaultFormatter.install(DefaultFormatter.java:105)
    	at javax.swing.text.InternationalFormatter.install(InternationalFormatter.java:268)
    	at javax.swing.JFormattedTextField.setFormatter(JFormattedTextField.java:443)
    	at javax.swing.JFormattedTextField.setValue(JFormattedTextField.java:767)
    	at javax.swing.JFormattedTextField.setFormatterFactory(JFormattedTextField.java:399)
    	at javax.swing.JSpinner$NumberEditor.<init>(JSpinner.java:1157)
    	at javax.swing.JSpinner$NumberEditor.<init>(JSpinner.java:1120)
    	at javax.swing.JSpinner$NumberEditor.<init>(JSpinner.java:1095)
    	at javax.swing.JSpinner.createEditor(JSpinner.java:218)
    	at javax.swing.JSpinner.setModel(JSpinner.java:260)
    Je pense que le problème doit trouver sa solution avec le JFormattedTextField, mais je ne sais pas comment recreer cet objet pour un affichage hexadecimal

    Cordialement
    Page sur Developpez : http://pbriand.developpez.com

  5. #5
    Membre chevronné Avatar de schniouf
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Décembre 2003
    Messages
    382
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : Luxembourg

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Décembre 2003
    Messages : 382
    Par défaut
    Si tu prend un JFormattedTexField, c'est facile pour l'hexa :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    field = new JFormattedTextField( new MaskFormatter("HH") ) ;
    Voir la doc de MaskFormatter : http://java.sun.com/j2se/1.4.2/docs/...Formatter.html

  6. #6
    Membre émérite
    Avatar de bpy1401
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2003
    Messages
    511
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 64
    Localisation : France, Eure (Haute Normandie)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2003
    Messages : 511
    Par défaut
    Bonjour

    Suite à vos conseils, j'ai essayé le code suivant , mais toujours sans succés

    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
    package org.valeo.base.dialog.baseconfiguration.util.numeric;
     
    import javax.swing.JSpinner;
    import javax.swing.JFormattedTextField;
    import javax.swing.JComponent;
    import javax.swing.JTextField;
    import javax.swing.text.MaskFormatter;
    import java.text.*;
     
    /**
     * <p>Titre : </p>
     *
     * <p>Description : </p>
     *
     * <p>Copyright : Copyright (c) 2005</p>
     *
     * <p>Société : VALEO</p>
     *
     * @author non attribuable
     * @version 1.0
     */
    public class HexaSpinner extends JSpinner {
      public HexaSpinner() {
        super();
     
        //Tweak the spinner's formatted text field.
        JFormattedTextField ftf = getTextField();
        if (ftf != null ) {
            ftf.setColumns(8); //specify more width than we need
            ftf.setHorizontalAlignment(JTextField.LEFT);
            MaskFormatter formatter = (MaskFormatter) ftf.getFormatter();
            try {
              formatter.setMask("HH");
            } catch (ParseException ex) {
              ex.printStackTrace();
            }
        }
     
     }
     
     
      public JFormattedTextField getTextField() {
          JComponent editor = getEditor();
          if (editor instanceof JSpinner.DefaultEditor) {
              return ((JSpinner.DefaultEditor)editor).getTextField();
          } else {
              System.err.println("Unexpected editor type: "
                                 + getEditor().getClass()
                                 + " isn't a descendant of DefaultEditor");
              return null;
          }
       }
    }

    mais j'obtiens alors :

    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
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JSpinner$NumberEditorFormatter
    	at org.valeo.base.dialog.baseconfiguration.util.numeric.HexaSpinner.<init>(HexaSpinner.java:31)
    	at org.valeo.base.dialog.baseconfiguration.example.ExampleConfigurationBox.PreCompileConfigurationPanel(ExampleConfigurationBox.java:62)
    	at org.valeo.base.dialog.baseconfiguration.ComponentConfigurationBox.CreatePreCompilePanel(ComponentConfigurationBox.java:78)
    	at org.valeo.base.dialog.baseconfiguration.ComponentConfigurationBox.<init>(ComponentConfigurationBox.java:46)
    	at org.valeo.base.dialog.baseconfiguration.example.ExampleConfigurationBox.<init>(ExampleConfigurationBox.java:39)
    	at org.valeo.base.menu.menuitem.ComponentConfiguration.actionPerformed(ComponentConfiguration.java:35)
    	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
    	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
    	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
    	at javax.swing.AbstractButton.doClick(AbstractButton.java:302)
    	at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1000)
    	at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1041)
    	at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:231)
    	at java.awt.Component.processMouseEvent(Component.java:5488)
    	at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
    	at java.awt.Component.processEvent(Component.java:5253)
    	at java.awt.Container.processEvent(Container.java:1966)
    	at java.awt.Component.dispatchEventImpl(Component.java:3955)
    	at java.awt.Container.dispatchEventImpl(Container.java:2024)
    	at java.awt.Component.dispatchEvent(Component.java:3803)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
    	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
    	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
    	at java.awt.Container.dispatchEventImpl(Container.java:2010)
    	at java.awt.Window.dispatchEventImpl(Window.java:1774)
    	at java.awt.Component.dispatchEvent(Component.java:3803)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    	at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

    c'est une vrai galère ces spinner !
    Cordialement
    Page sur Developpez : http://pbriand.developpez.com

Discussions similaires

  1. Réponses: 2
    Dernier message: 10/07/2007, 09h28
  2. Afficher le signe des nombres positifs
    Par vcattin dans le forum Access
    Réponses: 2
    Dernier message: 27/12/2006, 14h16
  3. afficher une suite de nombres dans une string
    Par hysah dans le forum C++
    Réponses: 4
    Dernier message: 27/04/2006, 18h51
  4. [MySQL] affiche ke un certain nombre des premier caractere d'une var
    Par Damarus dans le forum PHP & Base de données
    Réponses: 4
    Dernier message: 11/09/2005, 17h47
  5. [Debutant][JSpinner] rendre non editable.
    Par britou dans le forum Composants
    Réponses: 7
    Dernier message: 27/05/2004, 17h49

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