Java Code Examples for javax.swing.text.NumberFormatter

The following examples show how to use javax.swing.text.NumberFormatter. These examples are extracted from open source projects. 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 Project: pcgen   Source File: SkillInfoTab.java    License: 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
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 3
Source Project: MercuryTrade   Source File: ComponentsFactory.java    License: 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 4
Source Project: pcgen   Source File: SkillInfoTab.java    License: 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 5
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 6
Source Project: magarena   Source File: DecksFilterDialog.java    License: 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 7
Source Project: consulo   Source File: SingleIntegerFieldOptionsPanel.java    License: 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 8
Source Project: atdl4j   Source File: SwingNullableSpinner.java    License: 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 9
Source Project: netcdf-java   Source File: Field.java    License: 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());
    }
  }
}
 
Example 10
Source Project: marathonv5   Source File: IntegerEditor.java    License: Apache License 2.0 5 votes vote down vote up
public IntegerEditor(int min, int max) {
    super(new JFormattedTextField());
    ftf = (JFormattedTextField) getComponent();
    minimum = new Integer(min);
    maximum = new Integer(max);

    // Set up the editor for the integer cells.
    integerFormat = NumberFormat.getIntegerInstance();
    NumberFormatter intFormatter = new NumberFormatter(integerFormat);
    intFormatter.setFormat(integerFormat);
    intFormatter.setMinimum(minimum);
    intFormatter.setMaximum(maximum);

    ftf.setFormatterFactory(new DefaultFormatterFactory(intFormatter));
    ftf.setValue(minimum);
    ftf.setHorizontalAlignment(JTextField.TRAILING);
    ftf.setFocusLostBehavior(JFormattedTextField.PERSIST);

    // React when the user presses Enter while the editor is
    // active. (Tab is handled as specified by
    // JFormattedTextField's focusLostBehavior property.)
    ftf.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "check");
    ftf.getActionMap().put("check", new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            if (!ftf.isEditValid()) { // The text is invalid.
                if (userSaysRevert()) { // reverted
                    ftf.postActionEvent(); // inform the editor
                }
            } else
                try { // The text is valid,
                    ftf.commitEdit(); // so use it.
                    ftf.postActionEvent(); // stop editing
                } catch (java.text.ParseException exc) {
                }
        }
    });
}
 
Example 11
Source Project: marathonv5   Source File: ConversionPanel.java    License: Apache License 2.0 5 votes vote down vote up
/** Updates the text field when the main data model is updated. */
public void stateChanged(ChangeEvent e) {
    int min = sliderModel.getMinimum();
    int max = sliderModel.getMaximum();
    double value = sliderModel.getDoubleValue();
    NumberFormatter formatter = (NumberFormatter) textField.getFormatter();

    formatter.setMinimum(new Double(min));
    formatter.setMaximum(new Double(max));
    textField.setValue(new Double(value));
}
 
Example 12
Source Project: netbeans   Source File: AdvancedSecurityPanel.java    License: 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 13
Source Project: netbeans   Source File: AdvancedRMPanel.java    License: Apache License 2.0 5 votes vote down vote up
public AdvancedRMPanel(Binding binding, ConfigVersion cfgVersion) {
    super();
    this.binding = binding;
    this.cfgVersion = cfgVersion;

    milisecondsff = new DefaultFormatterFactory();
    NumberFormat millisecondsFormat = NumberFormat.getIntegerInstance();        
    millisecondsFormat.setGroupingUsed(false);
    NumberFormatter millisecondsFormatter = new NumberFormatter(millisecondsFormat);
    millisecondsFormat.setMaximumIntegerDigits(8);
    millisecondsFormatter.setCommitsOnValidEdit(true);
    millisecondsFormatter.setMinimum(0);
    millisecondsFormatter.setMaximum(99999999);
    milisecondsff.setDefaultFormatter(millisecondsFormatter);

    maxBufff = new DefaultFormatterFactory();
    NumberFormat maxBufFormat = NumberFormat.getIntegerInstance();
    maxBufFormat.setGroupingUsed(false);
    NumberFormatter maxBufFormatter = new NumberFormatter(maxBufFormat);
    maxBufFormat.setMaximumIntegerDigits(8);
    maxBufFormatter.setCommitsOnValidEdit(true);
    maxBufFormatter.setMinimum(0);
    maxBufFormatter.setMaximum(99999999);
    maxBufff.setDefaultFormatter(maxBufFormatter);

    initComponents();

    inSync = true;
    for (RMDeliveryAssurance assurance : RMDeliveryAssurance.values()) {
        deliveryAssuranceCombo.addItem(assurance);
    }
    inSync = false;
    
    sync();
    refresh();
}
 
Example 14
Source Project: netbeans   Source File: STSConfigServicePanel.java    License: 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 15
public NumberFormatterFactory() {
	super();
	final NumberFormat format = NumberFormat.getIntegerInstance();
	format.setGroupingUsed(false);
	final NumberFormatter nf = new NumberFormatter(format);
	setDefaultFormatter(nf);
	setDisplayFormatter(nf);
	setEditFormatter(nf);
}
 
Example 16
Source Project: JByteMod-Beta   Source File: ClassDialogue.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static JFormattedTextField createNumberField(Class<?> type, Object minValue, Object maxValue) {
  NumberFormat format = NumberFormat.getInstance();
  format.setGroupingUsed(false);
  format.setMaximumFractionDigits(10);
  NumberFormatter formatter = new NumberFormatter(format);
  formatter.setValueClass(type);
  formatter.setMinimum((Comparable) minValue);
  formatter.setMaximum((Comparable) maxValue);
  formatter.setAllowsInvalid(false);
  formatter.setCommitsOnValidEdit(true);
  formatter.setOverwriteMode(true);
  JFormattedTextField jftf = new JFormattedTextField(formatter);
  return jftf;
}
 
Example 17
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 18
Source Project: Carcassonne   Source File: GridSizeDialog.java    License: 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 19
Source Project: Carcassonne   Source File: TileQuantityPanel.java    License: 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 20
Source Project: protobuf-converter   Source File: AddBookView.java    License: 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 21
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 22
Source Project: bither-desktop-java   Source File: Numbers.java    License: 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 23
Source Project: bither-desktop-java   Source File: FormattedDecimalField.java    License: 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 24
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 25
/**
 * 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 26
Source Project: java-swing-tips   Source File: MainPanel.java    License: 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 27
Source Project: java-swing-tips   Source File: MainPanel.java    License: 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 28
Source Project: Girinoscope   Source File: CustomAxisEditionDialog.java    License: 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 29
Source Project: magarena   Source File: PreferencesDialog.java    License: 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 30
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();
}