Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSpinner: Increase length of editor box

I have a JSpinner that displays decimal values from 0.0 to 999.0. It seems to work fine, except for when it displays a number in the editor box that is four-digits long, such as 123.4; it then cuts off part of the final digit because it is not long enough.

So my question is: Does anyone know how to increase the length of the editor window of a JSpinner?

Thanks!

like image 357
spookymodem Avatar asked Sep 10 '11 20:09

spookymodem


1 Answers

You can get to the text field which in fact is a JFormattedTextField by

  • First calling getEditor() on your JSpinner to get the spinner's editor
  • cast the returned object to JSpinner.DefaultEditor
  • Then call getTextField() on this. Then you can set it's preferredSize if desired.

Edit: as noted by trashgod though, using a proper layout is paramount and being sure that the layouts you use are the best is probably the best way to solve this issue.

Edit 2: The above is wrong as setting the textfield's preferred size does nothing. You can however set the preferred size of the editor itself, and that works. e.g .,

import java.awt.Dimension;

import javax.swing.*;

public class SpinnerBigTextField {
   private static void createAndShowGui() {
      JSpinner spinner = new JSpinner(new SpinnerNumberModel(0.0, 0.0, 999.0,
            0.5));

      JPanel panel = new JPanel();
      panel.setPreferredSize(new Dimension(300, 100));
      panel.add(spinner);

      JComponent field = ((JSpinner.DefaultEditor) spinner.getEditor());
      Dimension prefSize = field.getPreferredSize();
      prefSize = new Dimension(200, prefSize.height);
      field.setPreferredSize(prefSize);

      JFrame frame = new JFrame("SpinnerBigTextField");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(panel);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
like image 192
Hovercraft Full Of Eels Avatar answered Oct 12 '22 22:10

Hovercraft Full Of Eels