12

How can I create a numeric text box in java swing , which has two buttons (up and down) which increments and decrements the value in the text box respectively. Also this text box must be editable with ONLY NUMERIC VALUES. Something like this

Numeric Text Box

I tried by placing two buttons near a text box and manually doing the operation on button click.

My try Text Box

Is there any other method in which I can do this in a better way and achieve a similar result as the first image.

Thanks :)

Balanivash
  • 6,709
  • 9
  • 32
  • 48

2 Answers2

20

Use JSpinner

How to use Spinners in java


Based on your comment:

SpinnerModel model = new SpinnerNumberModel(9.9, 1, 15, 0.1);     
JSpinner spinner = new JSpinner(model);
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
  • Can this be used to increment and decrement in steps of 0.1, cos, when I implemented the other way, float gave things like, `9.8000000000007` when decremented from `9.9` and similar problems – Balanivash Jun 22 '11 at 06:27
  • Use a [SpinnerNumberModel](http://download.oracle.com/javase/6/docs/api/javax/swing/SpinnerNumberModel.html) for this. Provide 0.1 in step to make it change value by 0.1. – Harry Joy Jun 22 '11 at 06:29
2

JSpinner need for allows numeric input only, required some hack for that in its Model, but your 2nd. picture looks like as two JButtons (with JButton#setFocucPainted(false)), and one JFormattedTextField with number Format, with min/maxDecimalPaces, with roundingMode

myDoubleFormat.setMinimumFractionDigits(2);
myDoubleForma.setMaximumFractionDigits(2);
myDoubleForma.setRoundingMode(RoundingMode.HALF_UP);

then Action from JButton will be

myFtdTextField.setValue(((Number) myFtdTextField.getValue()).doubleValue() +/- 0.1)
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • actually I need to create something similar to the first image, as i dont know how, I manually did it using two buttons and a text box. But think JSpinner did the trick.. :) Thanks :) – Balanivash Jun 22 '11 at 06:47
  • @Balanivash you are welcome :-) alternative always exist, about my post, nobody knows..., but for JSinner you have to implents this hack, read carrefully http://forums.oracle.com/forums/thread.jspa?messageID=9337792 – mKorbel Jun 22 '11 at 07:02