Some hints for hex Jspinner ? I s the approach correct

余生长醉 提交于 2020-01-13 20:21:02

问题


i want t make a JSpinner to spin hex values from 0x0000000 to 0xffffffff . Tried extending the abstractspinner model but failed . Is my approach correct and is there any other solution.some help would be really usefull


回答1:


Here is one way which might help you

import java.awt.BorderLayout; 
import java.text.ParseException; 

import javax.swing.JFormattedTextField; 
import javax.swing.JFrame; 
import javax.swing.JSpinner; 
import javax.swing.SpinnerNumberModel; 
import javax.swing.JFormattedTextField.AbstractFormatter; 
import javax.swing.text.DefaultFormatter; 
import javax.swing.text.DefaultFormatterFactory; 


public class HexSpinnerTest { 

  public static void main(String[] args) { 
     JFrame f = new JFrame(); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JSpinner sp = new JSpinner(new SpinnerNumberModel(0,0,10000,1)); 
     JSpinner.DefaultEditor editor = 
     (JSpinner.DefaultEditor)sp.getEditor(); 
     JFormattedTextField tf = editor.getTextField(); 
     tf.setFormatterFactory(new MyFormatterFactory()); 
     f.getContentPane().add(sp, BorderLayout.NORTH); 
     f.setSize(200,200); 
     f.setVisible(true); 
  }

  private static class MyFormatterFactory extends DefaultFormatterFactory { 
        public AbstractFormatter getDefaultFormatter() { 
           return new HexFormatter(); 
       } 
  } 

  private static class HexFormatter extends DefaultFormatter { 
      public Object stringToValue(String text) throws ParseException { 
         try { 
            return Long.valueOf(text, 16); 
         } catch (NumberFormatException nfe) { 
            throw new ParseException(text,0); 
         } 
     } 

     public String valueToString(Object value) throws ParseException { 
           return Integer.toHexString( 
              ((Integer)value).intValue()).toUpperCase(); 
     } 
 } 
} 

I have done it for 0 to 10000, which are getting converted to HEX.



来源:https://stackoverflow.com/questions/9758469/some-hints-for-hex-jspinner-i-s-the-approach-correct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!