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

  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 : 65
    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 920
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 50
    Localisation : Nouvelle-Calédonie

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

    Informations forums :
    Inscription : Août 2005
    Messages : 6 920
    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 : 65
    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 : 41
    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 : 65
    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

  7. #7
    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 : 41
    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
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    MaskFormatter formatter = (MaskFormatter) ftf.getFormatter();
            try {
              formatter.setMask("HH");
            } catch (ParseException ex) {
              ex.printStackTrace();
            }
    C'est là que ça plante, tu essaies de caster le formatter par défaut du Spinner (un javax.swing.JSpinner$NumberEditorFormatter) en MaskFormatter.
    Fait directement :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
            try {
              MaskFormatter formatter =  new MaskFormatter("HH");
              formatter.setMask( formatter  );
            } catch (ParseException ex) {
              ex.printStackTrace();
            }
    Mais même comme ça, je pense pas que le spinner te convertisse ta valeur en hexa quand tu cliques sur les flèches. Tu devrais implémenter ta propre classe héritant de SpinnerNumberModel

  8. #8
    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
    Citation Envoyé par schniouf
    Tu devrais implémenter ta propre classe héritant de SpinnerNumberModel
    C'est ce que je lui ai proposé, en forçant le type de getValue en String pour être sûr qu'il affiche en hexadécimal. Mais il y a incompatibilité avec le Formatter de l'editor, d'ou exception.

    Peut être en héritant d'un SpinnerListModel ?
    "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.

  9. #9
    Nouveau candidat au Club
    Inscrit en
    Juin 2007
    Messages
    2
    Détails du profil
    Informations forums :
    Inscription : Juin 2007
    Messages : 2
    Par défaut
    J'ai une solution pour le spinner hexadécimal.
    Je ne sais pas si c'est la plus courte mais elle permet de bien comprendre ce qu'il se passe entre le formatter, l'editor, le model et le spinner.

    Les classes que j'ai dérivées sont:
    public class HexFormatter extends DefaultFormatter;
    public class HexEditor extends DefaultEditor;
    public class SpinnerHexNumberModel extends AbstractSpinnerModel;
    public class HexJSpinner extends JSpinner;

    Je poste le code si ça intéresse toujours quelqu'un.

  10. #10
    Nouveau candidat au Club
    Inscrit en
    Juin 2007
    Messages
    2
    Détails du profil
    Informations forums :
    Inscription : Juin 2007
    Messages : 2
    Par défaut
    HexEditor.java

    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
    package julien.bramary.labspot;
     
    import java.text.ParseException;
     
    import javax.swing.JFormattedTextField;
    import javax.swing.JTextField;
    import javax.swing.JSpinner.DefaultEditor;
     
    @SuppressWarnings("serial")
    public class HexEditor extends DefaultEditor {
     
    	public HexEditor(HexJSpinner spinner) {
    		super(spinner);
    		SpinnerHexNumberModel model = spinner.getModel();
    		HexFormatter formatter = new HexFormatter(model.getMinimum(), model.getMaximum());
     
    		JFormattedTextField ftf = new JFormattedTextField(formatter);
    		ftf.setName("HexJSpinner.formattedTextField");
    		ftf.setValue(spinner.getValue());
    		ftf.addPropertyChangeListener(this);
    		ftf.setEditable(true);
    		ftf.setInheritsPopupMenu(true);
     
    		String toolTipText = spinner.getToolTipText();
    		if (toolTipText != null) {
    			ftf.setToolTipText(toolTipText);
    		}
     
    		if (!(spinner.getModel() instanceof SpinnerHexNumberModel)) {
    			throw new IllegalArgumentException(
    			"model not a SpinnerHexNumberModel");
    		}
     
    		ftf.setHorizontalAlignment(JTextField.RIGHT);
    		/* TBD - initializing the column width of the text field
    		 * is inaccurate and doing it here is tricky because 
    		 * the developer may configure the formatter later.
    		 */
    		try {
    			String maxString = formatter.valueToString(model.getMinimum());
    			String minString = formatter.valueToString(model.getMaximum());
    			ftf.setColumns(Math.max(maxString.length()+2,
    					minString.length()+2));
    		}
    		catch (ParseException e) {
    			// TBD should throw a chained error here
    		}
    		remove(getComponent(0));
    		add(ftf);
    	}
    }
    HexFormatter.java
    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
    package julien.bramary.labspot;
     
    import java.text.ParseException;
    import javax.swing.text.DefaultFormatter;
     
    @SuppressWarnings("serial")
    public class HexFormatter extends DefaultFormatter {
     
    	private Integer max;
    	private Integer min;
     
    	private boolean upper_case = true;
     
    	/**
             * Creates a HexFormatter.
             */
    	public HexFormatter(Integer min, Integer max) {
    		super();
    		this.max = max;
    		this.min = min;
    		setAllowsInvalid(false);
    		setCommitsOnValidEdit(true);
    		setOverwriteMode(true);
    	}
     
    	@Override
    	public Object stringToValue(String text) throws ParseException {
    		Integer ret = null;
    		if (text.equals("")) {
    			if (min != null) {
    				ret = min;
    			}
    			else {
    				ret = 0;
    			}
    		}
    		else {
    			try {
    				if (text.startsWith("0x"))
    					text = text.substring(2);
    				ret = Integer.parseInt(text, 16);
    			}
    			catch (NumberFormatException e) {
    				throw new ParseException("Err", 0);
    			}
    			if (max != null) {
    				if (ret > max) {
    					ret = max;
    					throw new ParseException("Err", 0);
    				}
    			}
    			if (min != null) {
    				if (ret < min) {
    					ret = min;
    					throw new ParseException("Err", 0);
    				}
    			}
    		}
    		return "0x"+Integer.toString(ret, 16);
    	}
     
    	@Override
    	public String valueToString(Object value) throws ParseException {
    		if (value instanceof String) {
    			String text = (String)value;
    			if (text.startsWith("0x"))
    				text = text.substring(2);
    			Integer ret = Integer.parseInt(text, 16);
    			if (max != null) {
    				if (ret > max) {
    					ret = max;
    				}
    			}
    			if (min != null) {
    				if (ret < min) {
    					ret = min;
    				}
    			}
    			String str = Integer.toString(ret, 16);
    			if (upper_case)
    				str = str.toUpperCase();
    			return "0x"+str;
    		}
    		else {
    			if (value instanceof Integer) {
    				int ret = (Integer)value; 
    				if (max != null) {
    					if (ret > max) {
    						ret = max;
    					}
    				}
    				if (min != null) {
    					if (ret < min) {
    						ret = min;
    					}
    				}
    				String str = Integer.toString(ret, 16);
    				if (upper_case)
    					str = str.toUpperCase();
    				return "0x"+str;
    			}
    		}
    		return "Bozo"; // is a bug if it happens
    	}
    }
    SpinnerHexNumberModel.java
    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
    package julien.bramary.labspot;
     
    import javax.swing.AbstractSpinnerModel;
     
    public class SpinnerHexNumberModel extends AbstractSpinnerModel
    {
    	protected int stepSize, value;
    	protected Integer minimum, maximum;
    	protected boolean upper_case;
    	protected String oldString;
     
    	public SpinnerHexNumberModel(int value, Integer minimum, Integer maximum, int stepSize) {
    		if ( ! (( minimum == null || value >= minimum ) && 
    				( maximum == null || value <= maximum ) )) {
    			throw new IllegalArgumentException("(minimum <= value <= maximum) is false");
    		}
    		this.value = value;
    		this.minimum = minimum;
    		this.maximum = maximum;
    		this.stepSize = stepSize;
    		this.upper_case = true;
    	}
     
    	public void setMinimum(Integer minimum) {
    		if ((minimum == null) ? (this.minimum != null) : !minimum.equals(this.minimum)) {
    			this.minimum = minimum;
    			fireStateChanged();
    		}
    	}
     
    	public Integer getMinimum() {
    		return minimum;
    	}
     
    	public void setMaximum(Integer maximum) {
    		if ((maximum == null) ? (this.maximum != null) : !maximum.equals(this.maximum)) {
    			this.maximum = maximum;
    			fireStateChanged();
    		}
    	}
     
    	public Integer getMaximum() {
    		return maximum;
    	}
     
    	public void setStepSize(int stepSize) {
    		if (stepSize != this.stepSize) {
    			this.stepSize = stepSize;
    			fireStateChanged();
    		}
    	}
     
    	public Number getStepSize() {
    		return stepSize;
    	}
     
    	protected int incrValue(int dir) 
    	{
    		int newValue;
    		newValue = this.value + (stepSize * dir);
     
    		if ( maximum != null && newValue > maximum) {
    			return maximum;
    		}
    		if ( minimum != null && newValue < minimum ) {
    			return minimum;
    		}
    		else {
    			return newValue;
    		}
    	}
     
    	public Object getNextValue() {
    		String ret = Integer.toString(incrValue(+1), 16);
    		return upper_case ? ret.toUpperCase() : ret;
    	}
     
    	public Object getPreviousValue() {
    		String ret = Integer.toString(incrValue(-1), 16);
    		return upper_case ? ret.toUpperCase() : ret;
    	}
     
    	public int getNumber() {
    		return value;
    	}
     
    	public Object getValue() {
    		String ret = Integer.toString(value, 16);
    		return upper_case ? "0x"+ret.toUpperCase() : "0x"+ret;
    	}
     
    	public void setValue(Object value) {
    		if ((value == null) || !(value instanceof String)) {
    			throw new IllegalArgumentException("illegal value");
    		}
    		String newString = (String)value;
    		if (newString.startsWith("0x"))
    			newString = newString.substring(2);
    		int newVal = Integer.parseInt(newString, 16);
    		if ( maximum != null && newVal > maximum) {
    			newVal = maximum;
    		}
    		if ( minimum != null && newVal < minimum ) {
    			newVal = minimum;
    		}
    		if (newVal != this.value) {
    			this.value = newVal;
    			oldString = newString;
    			fireStateChanged();
    		}
    		// Kludge for Case Auto-Correction ;)
    		else if (!newString.equals(oldString)) {
    			oldString = newString;
    			fireStateChanged();
    		}
    	}
    }
    HexJSpinner.java
    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
    package julien.bramary.labspot;
     
     
    import javax.swing.JComponent;
    import javax.swing.JSpinner;
    import javax.swing.SpinnerModel;
     
    @SuppressWarnings("serial")
    public class HexJSpinner extends JSpinner {
    	public HexJSpinner(SpinnerModel hex_model) {
    		super(hex_model);
    	}
     
    	@Override
    	protected JComponent createEditor(SpinnerModel model) {
    		return new HexEditor(this);
    	}
     
    	@Override
    	public SpinnerHexNumberModel getModel() {
    		return (SpinnerHexNumberModel)super.getModel();
    	}
     
    	public int getNumber() {
    		return getModel().getNumber();
    	}
    }
    Finally a small main to test the new widget:

    TestHexSpinner.java
    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 julien.bramary.labspot;
     
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
     
    import javax.swing.JFrame;
    import javax.swing.JLabel;
     
    @SuppressWarnings("serial")
    public class TestHexSpinner extends JFrame {
     
    	public static void main(String[] args) {
    		TestHexSpinner explorer = new TestHexSpinner();
    		explorer.run();
    	}
     
    	private void run() {
    		SpinnerHexNumberModel readAddrModel = new SpinnerHexNumberModel(0xFF, 0, 0xFFFFFF, 1);		
    		HexJSpinner readAddrSpin = new HexJSpinner(readAddrModel);
    		JLabel readAddrLabel = new JLabel("Hexadecimal Spinner :");
    		readAddrLabel.setLabelFor(readAddrSpin);
     
     
    		// Main Window
    		setLayout(new BorderLayout());
    		this.add(readAddrLabel, BorderLayout.NORTH);
    		this.add(readAddrSpin, BorderLayout.SOUTH);
     
    		setSize(new Dimension(150, 80));
    		setVisible(true);
     
    		addWindowListener(new WindowAdapter() {
    			public void windowClosing(WindowEvent e) {
    				System.exit(0);
    			}
    		});
    	}
     
    }

  11. #11
    Membre averti
    Profil pro
    Inscrit en
    Mai 2004
    Messages
    13
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2004
    Messages : 13
    Par défaut
    Merci bien pour le code.

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