javax.swing.text.NumberFormatter Java Examples

The following examples show how to use javax.swing.text.NumberFormatter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SkillInfoTab.java    From pcgen with GNU Lesser General Public License v2.1 7 votes vote down vote up
private SkillRankSpinnerEditor(SkillRankSpinnerModel model)
{
	super(model);
	this.model = model;

	DefaultEditor editor = new DefaultEditor(spinner);
	NumberFormatter formatter = new NumberFormatter(new DecimalFormat("#0.#")); //$NON-NLS-1$
	formatter.setValueClass(Float.class);
	DefaultFormatterFactory factory = new DefaultFormatterFactory(formatter);

	JFormattedTextField ftf = editor.getTextField();
	ftf.setEditable(true);
	ftf.setFormatterFactory(factory);
	ftf.setHorizontalAlignment(SwingConstants.RIGHT);

	spinner.setEditor(editor);
}
 
Example #2
Source File: SwingNullableSpinner.java    From atdl4j with MIT License 6 votes vote down vote up
private NumberEditorNull(JSpinner spinner, DecimalFormat format) {
	super(spinner);
	if (!(spinner.getModel() instanceof SpinnerNumberModelNull)) {
		return;
	}
	
	SpinnerNumberModelNull model = (SpinnerNumberModelNull) spinner.getModel();
	NumberFormatter formatter = new NumberEditorFormatterNull(model, format);
	DefaultFormatterFactory factory = new DefaultFormatterFactory(formatter);
	JFormattedTextField ftf = getTextField();
	ftf.setEditable(true);
	ftf.setFormatterFactory(factory);
	ftf.setHorizontalAlignment(JTextField.RIGHT);
	
	try {
		String maxString = formatter.valueToString(model.getMinimum());
		String minString = formatter.valueToString(model.getMaximum());
		ftf.setColumns(Math.max(maxString.length(), minString.length()));
	}
	catch (ParseException e) {
		// TBD should throw a chained error here
	}
}
 
Example #3
Source File: SingleIntegerFieldOptionsPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Sets integer number format to JFormattedTextField instance,
 * sets value of JFormattedTextField instance to object's field value,
 * synchronizes object's field value with the value of JFormattedTextField instance.
 *
 * @param textField  JFormattedTextField instance
 * @param owner      an object whose field is synchronized with {@code textField}
 * @param property   object's field name for synchronization
 */
public static void setupIntegerFieldTrackingValue(final JFormattedTextField textField,
                                                  final InspectionProfileEntry owner,
                                                  final String property) {
    NumberFormat formatter = NumberFormat.getIntegerInstance();
    formatter.setParseIntegerOnly(true);
    textField.setFormatterFactory(new DefaultFormatterFactory(new NumberFormatter(formatter)));
    textField.setValue(getPropertyValue(owner, property));
    final Document document = textField.getDocument();
    document.addDocumentListener(new DocumentAdapter() {
        @Override
        public void textChanged(DocumentEvent e) {
            try {
                textField.commitEdit();
                setPropertyValue(owner, property,
                        ((Number) textField.getValue()).intValue());
            } catch (ParseException e1) {
                // No luck this time
            }
        }
    });
}
 
Example #4
Source File: NumberPropertyEditor.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
public NumberPropertyEditor(Class type) {
  if (!Number.class.isAssignableFrom(type)) {
    throw new IllegalArgumentException("type must be a subclass of Number");
  }

  editor = new JFormattedTextField();
  this.type = type;
  ((JFormattedTextField)editor).setValue(getDefaultValue());
  ((JFormattedTextField)editor).setBorder(LookAndFeelTweaks.EMPTY_BORDER);

  // use a custom formatter to have numbers with up to 64 decimals
  NumberFormat format = NumberConverters.getDefaultFormat();

  ((JFormattedTextField) editor).setFormatterFactory(
      new DefaultFormatterFactory(new NumberFormatter(format))
  );
}
 
Example #5
Source File: SkillInfoTab.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
private SkillRankSpinnerEditor(SkillRankSpinnerModel model)
{
	super(model);
	this.model = model;

	DefaultEditor editor = new DefaultEditor(spinner);
	NumberFormatter formatter = new NumberFormatter(new DecimalFormat("#0.#")); //$NON-NLS-1$
	formatter.setValueClass(Float.class);
	DefaultFormatterFactory factory = new DefaultFormatterFactory(formatter);

	JFormattedTextField ftf = editor.getTextField();
	ftf.setEditable(true);
	ftf.setFormatterFactory(factory);
	ftf.setHorizontalAlignment(SwingConstants.RIGHT);

	spinner.setEditor(editor);
}
 
Example #6
Source File: ComponentsFactory.java    From MercuryTrade with MIT License 6 votes vote down vote up
public JFormattedTextField getIntegerTextField(Integer min, Integer max, Integer value) {
    NumberFormat format = NumberFormat.getInstance();
    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setValueClass(Integer.class);
    formatter.setMinimum(min);
    formatter.setMaximum(max);
    formatter.setAllowsInvalid(true);
    formatter.setCommitsOnValidEdit(false);

    JFormattedTextField field = new JFormattedTextField(formatter);
    field.setValue(value);
    field.setFont(REGULAR_FONT.deriveFont(scale * 18));
    field.setFocusLostBehavior(JFormattedTextField.PERSIST);
    field.setForeground(AppThemeColor.TEXT_DEFAULT);
    field.setCaretColor(AppThemeColor.TEXT_DEFAULT);
    field.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(AppThemeColor.BORDER, 1),
            BorderFactory.createLineBorder(AppThemeColor.TRANSPARENT, 3)
    ));
    field.setBackground(AppThemeColor.HEADER);
    return field;
}
 
Example #7
Source File: DecksFilterDialog.java    From magarena with GNU General Public License v3.0 6 votes vote down vote up
private void setLookAndFeel() {
    setOpaque(false);
    setLayout(migLayout);
    setPreferredSize(new Dimension(0, 30));
    // filter combo
    numericFilterCombo.setModel(new DefaultComboBoxModel<>(NumericFilter.values()));
    // spinner1
    sizeSpinner1.setVisible(false);
    // allow only numeric characters to be recognised.
    sizeSpinner1.setEditor(new JSpinner.NumberEditor(sizeSpinner1,"#"));
    final JFormattedTextField txt1 = ((JSpinner.NumberEditor) sizeSpinner1.getEditor()).getTextField();
    ((NumberFormatter)txt1.getFormatter()).setAllowsInvalid(false);
    // spinner2
    sizeSpinner2.setVisible(false);
    // allow only numeric characters to be recognised.
    sizeSpinner2.setEditor(new JSpinner.NumberEditor(sizeSpinner2,"#"));
    final JFormattedTextField txt2 = ((JSpinner.NumberEditor) sizeSpinner2.getEditor()).getTextField();
    ((NumberFormatter)txt2.getFormatter()).setAllowsInvalid(false);
}
 
Example #8
Source File: NumberPropertyEditor.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
public NumberPropertyEditor(Class type) {
  if (!Number.class.isAssignableFrom(type)) {
    throw new IllegalArgumentException("type must be a subclass of Number");
  }

  editor = new JFormattedTextField();
  this.type = type;
  ((JFormattedTextField)editor).setValue(getDefaultValue());
  ((JFormattedTextField)editor).setBorder(LookAndFeelTweaks.EMPTY_BORDER);

  // use a custom formatter to have numbers with up to 64 decimals
  NumberFormat format = NumberConverters.getDefaultFormat();

  ((JFormattedTextField) editor).setFormatterFactory(
      new DefaultFormatterFactory(new NumberFormatter(format))
  );
}
 
Example #9
Source File: FormattedDecimalField.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
/**
 * @param min           The minimum value
 * @param max           The maximum value
 * @param decimalPlaces The number of decimal places to show (padding as required)
 * @param maxLength     The maximum length
 */
public FormattedDecimalField(double min, double max, int decimalPlaces, int maxLength) {

    super();

    Preconditions.checkNotNull(min, "'min' must be present");
    Preconditions.checkNotNull(max, "'max' must be present");
    Preconditions.checkState(min < max, "'min' must be less than 'max'");

    Preconditions.checkState(decimalPlaces >= 0 && decimalPlaces < 15, "'decimalPlaces' must be in range [0,15)");

    // setInputVerifier(new ThemeAwareDecimalInputVerifier(min, max));

    setBackground(Themes.currentTheme.dataEntryBackground());

    // Build number formatters
    NumberFormatter defaultFormatter = new NumberFormatter();
    defaultFormatter.setValueClass(BigDecimal.class);

    NumberFormatter displayFormatter = Numbers.newDisplayFormatter(decimalPlaces, maxLength);
    NumberFormatter editFormatter = Numbers.newEditFormatter(decimalPlaces, maxLength);

    setFormatterFactory(new DefaultFormatterFactory(
            defaultFormatter,
            displayFormatter,
            editFormatter
    ));

}
 
Example #10
Source File: GrammarvizGuesserPane.java    From grammarviz2_src with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Provides a convenient integer formatter.
 * 
 * @return a formatter instance.
 */
private static NumberFormatter integerNumberFormatter() {
  NumberFormat format = NumberFormat.getInstance();
  NumberFormatter formatter = new NumberFormatter(format);
  formatter.setValueClass(Integer.class);
  formatter.setMinimum(0);
  formatter.setMaximum(Integer.MAX_VALUE);
  // If you want the value to be committed on each keystroke instead of focus lost
  formatter.setCommitsOnValidEdit(true);
  return formatter;
}
 
Example #11
Source File: Numbers.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
/**
 * @param decimalFormat The decimal format appropriate for this locale
 * @return A number formatter that is locale-aware and configured for doubles
 */
private static NumberFormatter newNumberFormatter(final DecimalFormat decimalFormat, final int maxEditLength) {

    // Create the number formatter with local-sensitive adjustments
    NumberFormatter displayFormatter = new NumberFormatter(decimalFormat) {

        // The max input length for the given symbol
        DocumentFilter documentFilter = new DocumentMaxLengthFilter(maxEditLength);

        @Override
        public Object stringToValue(String text) throws ParseException {
            // RU locale (and others) requires a non-breaking space for a grouping separator
            text = text.replace(' ', '\u00a0');
            return super.stringToValue(text);
        }

        @Override
        protected DocumentFilter getDocumentFilter() {
            return documentFilter;
        }

    };

    // Use a BigDecimal for widest value handling
    displayFormatter.setValueClass(BigDecimal.class);

    return displayFormatter;
}
 
Example #12
Source File: ImagePreviewWithSeries.java    From orbit-image-analysis with GNU General Public License v3.0 5 votes vote down vote up
public ImagePreviewWithSeries(final JFileChooser fc, final ChangeListener seriesChangeListner) {
    ImagePreview imagePreview = new ImagePreview(fc);
    final JSpinner seriesSpinner;
    SpinnerNumberModel spinnerModel;
    Integer current = new Integer(0);
    Integer min = new Integer(0);
    Integer max = new Integer(9999);
    Integer step = new Integer(1);
    spinnerModel = new SpinnerNumberModel(current, min, max, step);
    seriesSpinner = new JSpinner(spinnerModel);
    JFormattedTextField tf = ((JSpinner.DefaultEditor) seriesSpinner.getEditor()).getTextField();
    tf.setInputVerifier(new IntInputVerifier(0,min,max));
    ((NumberFormatter) tf.getFormatter()).setAllowsInvalid(false);

    JLabel label = new JLabel("Series / Scene:");
    setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
    JPanel seriesPanel = new JPanel();
    seriesPanel.add(label);
    seriesPanel.add(seriesSpinner);
    add(seriesPanel);
    add(imagePreview);

    this.seriesChangeListner = seriesChangeListner;
    
   seriesSpinner.addChangeListener(new ChangeListener() {
       @Override
       public void stateChanged(ChangeEvent e) {
           int series = (Integer)seriesSpinner.getValue();
           logger.debug("selected series: "+series);
           if (ImagePreviewWithSeries.this.seriesChangeListner!=null) {
               ImagePreviewWithSeries.this.seriesChangeListner.stateChanged(new ChangeEvent(new Integer(series)));
           }
           File[] files = fc.getSelectedFiles();
           fc.setSelectedFiles(null);
           fc.setSelectedFiles(files);
       }
   });

}
 
Example #13
Source File: AddBookView.java    From protobuf-converter with MIT License 5 votes vote down vote up
public AddBookView(final JFrame windowFrame) {
	form = new JPanel();
	form.setLayout(null);
	form.setBounds(0, 210, 250, 250);

	titleLable = new JLabel("Title");
	titleLable.setBounds(10, 10, 80, 25);
	form.add(titleLable);

	titleText = new JTextField(20);
	titleText.setBounds(80, 10, 160, 25);
	form.add(titleText);

	authorLabel = new JLabel("Author");
	authorLabel.setBounds(10, 40, 80, 25);
	form.add(authorLabel);
	authorText = new JTextField(20);
	authorText.setBounds(80, 40, 160, 25);
	form.add(authorText);

	pageLabel = new JLabel("Pages");
	pageLabel.setBounds(10, 70, 80, 25);
	form.add(pageLabel);
	NumberFormatter numberFormatter = new NumberFormatter(NumberFormat.getIntegerInstance());
	numberFormatter.setValueClass(Integer.class);
	numberFormatter.setAllowsInvalid(false);
	numberFormatter.setMinimum(1);
	pageText = new JFormattedTextField(numberFormatter);
	pageText.setBounds(80, 70, 160, 25);
	form.add(pageText);

	addButton = new JButton("Add");
	addButton.setBounds(160, 100, 80, 25);
	form.add(addButton);
	addButton.addActionListener(this);

	windowFrame.add(form);
}
 
Example #14
Source File: TileQuantityPanel.java    From Carcassonne with Eclipse Public License 2.0 5 votes vote down vote up
private void createTextField(int initialQuantity) {
    NumberFormatter formatter = new NumberFormatter(NumberFormat.getIntegerInstance());
    formatter.setMinimum(0);
    formatter.setMaximum(99);
    formatter.setAllowsInvalid(false);
    formatter.setCommitsOnValidEdit(true);
    textField = new JFormattedTextField(formatter);
    setQuantity(initialQuantity);
    add(textField, BorderLayout.SOUTH);
}
 
Example #15
Source File: GridSizeDialog.java    From Carcassonne with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a number formatter that enforces the valid minimum and maximum values for the text fields.
 */
private NumberFormatter createNumberFormatter() {
    NumberFormatter formatter = new NumberFormatter(NumberFormat.getInstance());
    formatter.setValueClass(Integer.class);
    formatter.setMinimum(MIN_VALUE);
    formatter.setMaximum(MAX_VALUE);
    return formatter;
}
 
Example #16
Source File: MuleRemoteDebuggerConfPanel.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
private void createUIComponents() {
    NumberFormat format = NumberFormat.getInstance();
    format.setGroupingUsed(false);
    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setValueClass(Integer.class);
    formatter.setMaximum(65535);
    formatter.setAllowsInvalid(false);
    formatter.setCommitsOnValidEdit(true);
    portTextField = new JFormattedTextField(formatter);
    jvmPortTextField = new JFormattedTextField(formatter);

    appsMap = new JBTable(new ModulesTableModel());

}
 
Example #17
Source File: AdvancedSecurityPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public AdvancedSecurityPanel(Binding binding, ConfigVersion cfgVersion) {
    this.binding = binding;
    this.cfgVersion = cfgVersion;
    
    freshnessff = new DefaultFormatterFactory();
    NumberFormat freshnessFormat = NumberFormat.getIntegerInstance();
    freshnessFormat.setGroupingUsed(false);
    NumberFormatter freshnessFormatter = new NumberFormatter(freshnessFormat);
    freshnessFormat.setMaximumIntegerDigits(8);
    freshnessFormatter.setCommitsOnValidEdit(true);
    freshnessFormatter.setMinimum(0);
    freshnessFormatter.setMaximum(99999999);
    freshnessff.setDefaultFormatter(freshnessFormatter);
            
    skewff = new DefaultFormatterFactory();
    NumberFormat skewFormat = NumberFormat.getIntegerInstance();
    skewFormat.setGroupingUsed(false);
    NumberFormatter skewFormatter = new NumberFormatter(skewFormat);
    skewFormat.setMaximumIntegerDigits(8);
    skewFormatter.setCommitsOnValidEdit(true);
    skewFormatter.setMinimum(0);
    skewFormatter.setMaximum(99999999);
    skewff.setDefaultFormatter(skewFormatter);

    initComponents();
    
    sync();
}
 
Example #18
Source File: STSConfigServicePanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Creates new form STSConfigServicePanel
 */
public STSConfigServicePanel( Project p, Binding binding, ConfigVersion cfgVersion) {
    this.project = p;
    this.binding = binding;
    this.cfgVersion = cfgVersion;

    lifeTimeDff = new DefaultFormatterFactory();
    NumberFormat lifetimeFormat = NumberFormat.getIntegerInstance();
    lifetimeFormat.setGroupingUsed(false);
    lifetimeFormat.setParseIntegerOnly(true);
    lifetimeFormat.setMaximumFractionDigits(0);
    NumberFormatter lifetimeFormatter = new NumberFormatter(lifetimeFormat);
    lifetimeFormatter.setCommitsOnValidEdit(true);
    lifetimeFormatter.setMinimum(0);
    lifeTimeDff.setDefaultFormatter(lifetimeFormatter);

    initComponents();

    inSync = true;
    ServiceProvidersTablePanel.ServiceProvidersTableModel tablemodel = new ServiceProvidersTablePanel.ServiceProvidersTableModel();
    this.remove(serviceProvidersPanel);
    
    STSConfiguration stsConfig = ProprietarySecurityPolicyModelHelper.getSTSConfiguration(binding);
    if (stsConfig == null) {
        stsConfig = ProprietarySecurityPolicyModelHelper.createSTSConfiguration(binding);
    }
    serviceProvidersPanel = new ServiceProvidersTablePanel(tablemodel, stsConfig, cfgVersion);
    ((ServiceProvidersTablePanel)serviceProvidersPanel).populateModel();
    inSync = false;

    sync();
    
}
 
Example #19
Source File: PreferencesDialog.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
private NumberFormatter getPortValueFormatter() {
    NumberFormat plainIntegerFormat = NumberFormat.getInstance();
    plainIntegerFormat.setGroupingUsed(false);                      // no commas

    NumberFormatter portFormatter = new NumberFormatter(plainIntegerFormat);
    portFormatter.setValueClass(Integer.class);
    portFormatter.setAllowsInvalid(false);
    portFormatter.setMinimum(0);
    portFormatter.setMaximum(65535);
    return portFormatter;
}
 
Example #20
Source File: IntegerField.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new integer field.
 *
 * @param min the min
 * @param max the max
 * @param initialValue the initial value
 */
public IntegerField(int min, int max, int initialValue) {
  super();

  NumberFormatter formatter = new NumberFormatter(numberFormat);
  formatter.setMinimum(min);
  formatter.setMaximum(max);
  formatter.setCommitsOnValidEdit(true);
  setFormatter(formatter);

  setValue(initialValue);
}
 
Example #21
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private static DefaultFormatterFactory makeFFactory(DecimalFormatSymbols dfs) {
  DecimalFormat format = new DecimalFormat("0.00", dfs);

  NumberFormatter displayFormatter = new NumberFormatter(format);
  displayFormatter.setValueClass(Double.class);

  NumberFormatter editFormatter = new NumberFormatter(format);
  editFormatter.setValueClass(Double.class);
  return new DefaultFormatterFactory(displayFormatter, displayFormatter, editFormatter);
}
 
Example #22
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private static DefaultFormatterFactory makeFFactory(SpinnerNumberModel m) { // DecimalFormatSymbols dfs) {
  NumberFormat format = new DecimalFormat("####0"); // , dfs);
  NumberFormatter editFormatter = new NumberFormatter(format) {
    // @Override protected DocumentFilter getDocumentFilter() {
    //   return new IntegerDocumentFilter();
    // }

    @Override public Object stringToValue(String text) throws ParseException {
      try {
        Long.parseLong(text);
      } catch (NumberFormatException ex) {
        throw (ParseException) new ParseException(ex.getMessage(), 0).initCause(ex);
      }
      Object o = format.parse(text);
      if (o instanceof Long) {
        Long val = (Long) format.parse(text);
        Long max = (Long) m.getMaximum();
        Long min = (Long) m.getMinimum();
        if (max.compareTo(val) < 0 || min.compareTo(val) > 0) {
          throw new ParseException("out of bounds", 0);
        }
        return val;
      }
      throw new ParseException("not Long", 0);
    }
  };
  // editFormatter.setAllowsInvalid(false);
  // editFormatter.setCommitsOnValidEdit(true);
  editFormatter.setValueClass(Long.class);
  NumberFormatter displayFormatter = new NumberFormatter(format);
  return new DefaultFormatterFactory(displayFormatter, displayFormatter, editFormatter);
}
 
Example #23
Source File: CustomAxisEditionDialog.java    From Girinoscope with Apache License 2.0 5 votes vote down vote up
private JFormattedTextField createMumberField(List<NumberFormatter> dynamicFormatters) {
    final NumberFormatter defaultFormatter = new NumberFormatter(new DecimalFormat(axisBuilder.getFormat()));
    final NumberFormatter displayFormatter = new NumberFormatter(new DecimalFormat(axisBuilder.getFormat()));
    final NumberFormatter editFormatter = new NumberFormatter(new DecimalFormat());

    dynamicFormatters.add(defaultFormatter);
    dynamicFormatters.add(displayFormatter);

    JFormattedTextField numberField = new JFormattedTextField( //
            new DefaultFormatterFactory(defaultFormatter, displayFormatter, editFormatter));
    numberField.setColumns(12);
    return numberField;
}
 
Example #24
Source File: PreferencesDialog.java    From magarena with GNU General Public License v3.0 5 votes vote down vote up
private JPanel getNetworkSettingsPanel() {
    final Proxy proxy = config.getProxy();
    //
    proxyComboBox.setModel(new DefaultComboBoxModel<>(Proxy.Type.values()));
    proxyComboBox.setFocusable(false);
    proxyComboBox.addActionListener(this);
    proxyComboBox.setSelectedItem(proxy.type());
    //
    // allow only numeric characters to be recognised.
    proxyPortSpinner.setEditor(new JSpinner.NumberEditor(proxyPortSpinner, "#"));
    final JFormattedTextField txt1 = ((JSpinner.NumberEditor) proxyPortSpinner.getEditor()).getTextField();
    ((NumberFormatter) txt1.getFormatter()).setAllowsInvalid(false);
    //
    if (proxy != Proxy.NO_PROXY) {
        proxyAddressTextField.setText(proxy.address().toString());
        proxyPortSpinner.setValue(((InetSocketAddress) proxy.address()).getPort());
    }
    // layout components
    final JPanel panel = new JPanel(new MigLayout("flowx, wrap 2, insets 16, gapy 4"));
    panel.add(getCaptionLabel(MText.get(_S12)));
    panel.add(proxyComboBox, "w 140!");
    panel.add(getCaptionLabel(MText.get(_S13)));
    panel.add(proxyAddressTextField, "w 100%");
    panel.add(getCaptionLabel(MText.get(_S14)));
    panel.add(proxyPortSpinner, "w 60!");
    return panel;
}
 
Example #25
Source File: NoGroupingSpinner.java    From microba with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public NoGroupingNumberEditor(JSpinner spinner, SpinnerModel model) {
	super(spinner);
	JFormattedTextField ftf = (JFormattedTextField) this
			.getComponent(0);
	NumberFormat fmt = NumberFormat.getIntegerInstance();
	fmt.setGroupingUsed(false);
	ftf.setFormatterFactory(new DefaultFormatterFactory(
			new NumberFormatter(fmt)));
	revalidate();
}
 
Example #26
Source File: Numbers.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
/**
 * @param decimalFormat The decimal format appropriate for this locale
 * @return A number formatter that is locale-aware and configured for doubles
 */
private static NumberFormatter newNumberFormatter(final DecimalFormat decimalFormat, final int maxEditLength) {

    // Create the number formatter with local-sensitive adjustments
    NumberFormatter displayFormatter = new NumberFormatter(decimalFormat) {

        // The max input length for the given symbol
        DocumentFilter documentFilter = new DocumentMaxLengthFilter(maxEditLength);

        @Override
        public Object stringToValue(String text) throws ParseException {
            // RU locale (and others) requires a non-breaking space for a grouping separator
            text = text.replace(' ', '\u00a0');
            return super.stringToValue(text);
        }

        @Override
        protected DocumentFilter getDocumentFilter() {
            return documentFilter;
        }

    };

    // Use a BigDecimal for widest value handling
    displayFormatter.setValueClass(BigDecimal.class);

    return displayFormatter;
}
 
Example #27
Source File: FormattedDecimalField.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
/**
 * @param min           The minimum value
 * @param max           The maximum value
 * @param decimalPlaces The number of decimal places to show (padding as required)
 * @param maxLength     The maximum length
 */
public FormattedDecimalField(double min, double max, int decimalPlaces, int maxLength) {

    super();

    Preconditions.checkNotNull(min, "'min' must be present");
    Preconditions.checkNotNull(max, "'max' must be present");
    Preconditions.checkState(min < max, "'min' must be less than 'max'");

    Preconditions.checkState(decimalPlaces >= 0 && decimalPlaces < 15, "'decimalPlaces' must be in range [0,15)");

    // setInputVerifier(new ThemeAwareDecimalInputVerifier(min, max));

    setBackground(Themes.currentTheme.dataEntryBackground());

    // Build number formatters
    NumberFormatter defaultFormatter = new NumberFormatter();
    defaultFormatter.setValueClass(BigDecimal.class);

    NumberFormatter displayFormatter = Numbers.newDisplayFormatter(decimalPlaces, maxLength);
    NumberFormatter editFormatter = Numbers.newEditFormatter(decimalPlaces, maxLength);

    setFormatterFactory(new DefaultFormatterFactory(
            defaultFormatter,
            displayFormatter,
            editFormatter
    ));

}
 
Example #28
Source File: ImageInfoEditor.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private void editSliderSample(MouseEvent evt, final int sliderIndex) {
    final PropertyContainer vc = new PropertyContainer();
    vc.addProperty(Property.create("sample", getSliderSample(sliderIndex)));
    vc.getDescriptor("sample").setDisplayName("sample");
    vc.getDescriptor("sample").setUnit(getModel().getParameterUnit());
    final ValueRange valueRange;
    if (sliderIndex == 0) {
        valueRange = new ValueRange(Double.NEGATIVE_INFINITY, round(getMaxSliderSample(sliderIndex)));
    } else if (sliderIndex == getSliderCount() - 1) {
        valueRange = new ValueRange(round(getMinSliderSample(sliderIndex)), Double.POSITIVE_INFINITY);
    } else {
        valueRange = new ValueRange(round(getMinSliderSample(sliderIndex)), round(getMaxSliderSample(sliderIndex)));
    }
    vc.getDescriptor("sample").setValueRange(valueRange);

    final BindingContext ctx = new BindingContext(vc);
    final NumberFormatter formatter = new NumberFormatter(new DecimalFormat("#0.0#"));
    formatter.setValueClass(Double.class); // to ensure that double values are returned
    final JFormattedTextField field = new JFormattedTextField(formatter);
    field.setColumns(11);
    field.setHorizontalAlignment(JFormattedTextField.RIGHT);
    ctx.bind("sample", field);

    showPopup(evt, field);

    ctx.addPropertyChangeListener("sample", pce -> {
        hidePopup();
        setSliderSample(sliderIndex, (Double) ctx.getBinding("sample").getPropertyValue());
        computeZoomInToSliderLimits();
        applyChanges();
    });
}
 
Example #29
Source File: Continuous1BandBasicForm.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private JFormattedTextField getNumberTextField(double value) {
    final NumberFormatter formatter = new NumberFormatter(new DecimalFormat("0.0############"));
    formatter.setValueClass(Double.class); // to ensure that double values are returned
    final JFormattedTextField numberField = new JFormattedTextField(formatter);
    numberField.setValue(value);
    final Dimension preferredSize = numberField.getPreferredSize();
    preferredSize.width = 70;
    numberField.setPreferredSize(preferredSize);
    return numberField;
}
 
Example #30
Source File: Field.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void showFormatInfo(JFormattedTextField tf) {
  JFormattedTextField.AbstractFormatter ff = tf.getFormatter();
  System.out.println("AbstractFormatter  " + ff.getClass().getName());
  if (ff instanceof NumberFormatter) {
    NumberFormatter nf = (NumberFormatter) ff;
    Format f = nf.getFormat();
    System.out.println(" Format  = " + f.getClass().getName());
    if (f instanceof NumberFormat) {
      NumberFormat nfat = (NumberFormat) f;
      System.out.println(" getMinimumIntegerDigits=" + nfat.getMinimumIntegerDigits());
      System.out.println(" getMaximumIntegerDigits=" + nfat.getMaximumIntegerDigits());
      System.out.println(" getMinimumFractionDigits=" + nfat.getMinimumFractionDigits());
      System.out.println(" getMaximumFractionDigits=" + nfat.getMaximumFractionDigits());
    }
    if (f instanceof DecimalFormat) {
      DecimalFormat df = (DecimalFormat) f;
      System.out.println(" Pattern  = " + df.toPattern());
    }
  }
}