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
Asked
Active
Viewed 913 times
2
-
1Can you show what you've tried so far? – Hovercraft Full Of Eels Mar 18 '12 at 12:56
-
1Maybe a spinner is not the best component to be choosing from 268,435,456 possible values. BTW - what is it that requires a 7 'digit'(?) hex value? – Andrew Thompson Mar 18 '12 at 13:05
-
well it is for configuring the counting limits of a high speed motorand it is a 4 byte value ff ff ff ff – cornercoder Mar 18 '12 at 13:12
1 Answers
7
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.

kleopatra
- 51,061
- 28
- 99
- 211

Rahul Borkar
- 2,742
- 3
- 24
- 38
-
1Consider using `Long.valueOf(...)` and `Long.toHexString(...)` rather than the Integer variants. – Hovercraft Full Of Eels Mar 18 '12 at 13:32
-
@HovercraftFullOfEels, gr8 dude, thanks for that, I am editing now – Rahul Borkar Mar 18 '12 at 13:34
-
This code does not work correctly, if the user enters a value directly into the text field instead of using the up/down arrows. The input value is also accepted if it is out of range, for example > 2710h (10000d). The normal behaviour of a JSpinner is to also reject directly input values if they are out of range. – Markus Jan 19 '23 at 13:37