JSpinner: Increase length of editor box

前端 未结 5 474
一整个雨季
一整个雨季 2020-12-06 06:30

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, su

5条回答
  •  醉梦人生
    2020-12-06 07:12

    As FontMetrics vary from one platform to the next, it's better to rely on the component's own calculation of preferred size. This example shows a spectrum of JSpinner sizes for various min and max values. Note in particular that FlowLayout "lets each component assume its natural (preferred) size."

    enter image description here

    import java.awt.EventQueue;
    import java.awt.FlowLayout;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JSpinner;
    import javax.swing.SpinnerNumberModel;
    
    /** @see http://stackoverflow.com/questions/7374659 */
    public class SpinnerTest extends Box {
    
        private static final double STEP = 0.1d;
        private static final String FORMAT = "0.0000000000";
    
        public SpinnerTest(int axis) {
            super(axis);
            for (int i = 0; i < 8; i++) {
                int v = (int) Math.pow(10, i);
                this.add(genParamPanel((i + 1) + ":", -v, v));
            }
        }
    
        private JPanel genParamPanel(String name, double min, double max) {
            JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
            JLabel label = new JLabel(name, JLabel.TRAILING);
            JSpinner js = new JSpinner(new SpinnerNumberModel(min, min, max, STEP));
            js.setEditor(new JSpinner.NumberEditor(js, FORMAT));
            panel.add(label);
            panel.add(js);
            return panel;
        }
    
        private void display() {
            JFrame f = new JFrame("SpinnerTest");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(this);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    new SpinnerTest(BoxLayout.Y_AXIS).display();
                }
            });
        }
    }
    

提交回复
热议问题