Java Code Examples for javax.swing.text.DefaultFormatter

The following examples show how to use javax.swing.text.DefaultFormatter. 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: gcs   Source File: ReactionBonusEditor.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected void rebuildSelf(FlexGrid grid, FlexRow right) {
    ReactionBonus bonus = (ReactionBonus) getFeature();
    FlexRow       row   = new FlexRow();
    row.add(addChangeBaseTypeCombo());
    LeveledAmount amount = bonus.getAmount();
    row.add(addLeveledAmountField(amount, -99999, 99999));
    row.add(addLeveledAmountCombo(amount, false));
    row.add(new FlexSpacer(0, 0, true, false));
    grid.add(row, 0, 0);

    row = new FlexRow();
    row.setInsets(new Insets(0, 20, 0, 0));

    DefaultFormatter formatter = new DefaultFormatter();
    formatter.setOverwriteMode(false);
    mSituationField = new EditorField(new DefaultFormatterFactory(formatter), this, SwingConstants.LEFT, bonus.getSituation(), null);
    add(mSituationField);
    row.add(mSituationField);
    row.add(new FlexSpacer(0, 0, true, false));
    grid.add(row, 1, 0);
}
 
Example 2
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
private MainPanel() {
  super(new GridLayout(3, 1));

  JSpinner spinner = new JSpinner(makeSpinnerNumberModel());
  JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) spinner.getEditor();
  JFormattedTextField.AbstractFormatter formatter = editor.getTextField().getFormatter();
  if (formatter instanceof DefaultFormatter) {
    ((DefaultFormatter) formatter).setAllowsInvalid(false);
  }

  add(makeTitledPanel("Default", new JSpinner(makeSpinnerNumberModel())));
  add(makeTitledPanel("NumberFormatter#setAllowsInvalid(false)", spinner));
  add(makeTitledPanel("BackgroundColor", new WarningSpinner(makeSpinnerNumberModel())));
  setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
  setPreferredSize(new Dimension(320, 240));
}
 
Example 3
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 6 votes vote down vote up
protected LocalDateTimeEditor(JSpinner spinner, String dateFormatPattern) {
  super(spinner);
  if (!(spinner.getModel() instanceof SpinnerLocalDateTimeModel)) {
    throw new IllegalArgumentException("model not a SpinnerLocalDateTimeModel");
  }
  dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormatPattern);
  model = (SpinnerLocalDateTimeModel) spinner.getModel();
  DefaultFormatter formatter = new LocalDateTimeFormatter();

  EventQueue.invokeLater(() -> {
    formatter.setValueClass(LocalDateTime.class);
    JFormattedTextField ftf = getTextField();
    try {
      String maxString = formatter.valueToString(model.getStart());
      String minString = formatter.valueToString(model.getEnd());
      ftf.setColumns(Math.max(maxString.length(), minString.length()));
    } catch (ParseException ex) {
      // PENDING: hmuller
      ex.printStackTrace();
      UIManager.getLookAndFeel().provideErrorFeedback(ftf);
    }
    ftf.setHorizontalAlignment(SwingConstants.LEFT);
    ftf.setEditable(true);
    ftf.setFormatterFactory(new DefaultFormatterFactory(formatter));
  });
}
 
Example 4
public NumberEditor(String fieldName, Object obj, Field field, int index, Class<?> type, SWFType swfType) {
    setSize(100, getSize().height);
    setMaximumSize(getSize());
    this.obj = obj;
    this.field = field;
    this.index = index;
    this.type = type;
    this.swfType = swfType;
    this.fieldName = fieldName;

    reset();
    JFormattedTextField jtf = ((JSpinner.NumberEditor) getEditor()).getTextField();
    DefaultFormatter formatter = (DefaultFormatter) jtf.getFormatter();
    formatter.setCommitsOnValidEdit(true);

}
 
Example 5
Source Project: ghidra   Source File: AbstractTextFilter.java    License: Apache License 2.0 5 votes vote down vote up
private JComponent createComponent(String filterName) {
	final JPanel panel = new JPanel(new BorderLayout());
	Border paddingBorder = BorderFactory.createEmptyBorder(1, 5, 1, 5);
	Border outsideBorder = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
	panel.setBorder(BorderFactory.createCompoundBorder(outsideBorder, paddingBorder));

	DefaultFormatterFactory factory = new DefaultFormatterFactory(new DefaultFormatter());
	textField = new FilterFormattedTextField(factory, defaultValue);
	textField.setName(filterName + " Field"); // for debugging 	
	textField.setColumns(20);
	textField.setMinimumSize(textField.getPreferredSize());

	// we handle updates in real time, so ignore focus events, which trigger excess filtering
	textField.disableFocusEventProcessing();

	JLabel label = new GDLabel(filterName + ": ");
	panel.add(label, BorderLayout.WEST);
	panel.add(textField, BorderLayout.CENTER);

	StatusLabel nameFieldStatusLabel = new StatusLabel(textField, defaultValue);
	textField.addFilterStatusListener(nameFieldStatusLabel);
	textField.addFilterStatusListener(status -> fireStatusChanged(status));

	final JLayeredPane layeredPane = new JLayeredPane();
	layeredPane.add(panel, BASE_COMPONENT_LAYER);
	layeredPane.add(nameFieldStatusLabel, HOVER_COMPONENT_LAYER);

	layeredPane.setPreferredSize(panel.getPreferredSize());
	layeredPane.addComponentListener(new ComponentAdapter() {
		@Override
		public void componentResized(java.awt.event.ComponentEvent e) {
			Dimension preferredSize = layeredPane.getSize();
			panel.setBounds(0, 0, preferredSize.width, preferredSize.height);
			panel.validate();
		}
	});

	return layeredPane;
}
 
Example 6
private static void testDefaultFormatter(DefaultFormatter formatter ) {
    try {
        System.out.println("formatter: " + formatter.getClass());
        formatter.setValueClass(UserValueClass.class);
        UserValueClass userValue = (UserValueClass) formatter.stringToValue("test");

        if (!userValue.str.equals("test")) {
            throw new RuntimeException("String value is wrong!");
        }
    } catch (ParseException ex) {
        throw new RuntimeException(ex);
    }

}
 
Example 7
Source Project: gcs   Source File: EditorPanel.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * @param compare The current string compare object.
 * @return The field that allows a string comparison to be changed.
 */
protected EditorField addStringCompareField(StringCriteria compare) {
    DefaultFormatter formatter = new DefaultFormatter();
    formatter.setOverwriteMode(false);
    EditorField field = new EditorField(new DefaultFormatterFactory(formatter), this, SwingConstants.LEFT, compare.getQualifier(), null);
    field.putClientProperty(StringCriteria.class, compare);
    add(field);
    return field;
}
 
Example 8
Source Project: gcs   Source File: AdvantageEditor.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private EditorField createField(String text, String prototype, String tooltip) {
    DefaultFormatter formatter = new DefaultFormatter();
    formatter.setOverwriteMode(false);
    EditorField field = new EditorField(new DefaultFormatterFactory(formatter), this, SwingConstants.LEFT, text, prototype, tooltip);
    field.setEnabled(mIsEditable);
    add(field);
    return field;
}
 
Example 9
Source Project: gcs   Source File: WeaponEditor.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Creates a new text field.
 *
 * @param protoValue A prototype value. If not {@code null}, will be used to set the only size
 *                   the field can have.
 * @param tooltip    The tooltip to set on the field.
 * @return The newly created field.
 */
protected EditorField createTextField(String protoValue, String tooltip) {
    DefaultFormatter formatter = new DefaultFormatter();
    formatter.setOverwriteMode(false);
    EditorField field = new EditorField(new DefaultFormatterFactory(formatter), this, SwingConstants.LEFT, "", protoValue, tooltip);
    if (protoValue != null) {
        UIUtilities.setToPreferredSizeOnly(field);
    }
    return field;
}
 
Example 10
Source Project: sldeditor   Source File: IntegerSpinner.java    License: GNU General Public License v3.0 5 votes vote down vote up
/** Instantiates a new value spinner. */
public IntegerSpinner(int min, int max, int stepSize) {
    SpinnerNumberModel model = new SpinnerNumberModel(min, min, max, stepSize);
    setModel(model);

    JComponent comp = getEditor();
    final JFormattedTextField field = (JFormattedTextField) comp.getComponent(0);
    DefaultFormatter formatter = (DefaultFormatter) field.getFormatter();
    formatter.setCommitsOnValidEdit(true);
    addChangeListener(
            new ChangeListener() {
                private double oldValue = Double.MAX_VALUE;

                @Override
                public void stateChanged(ChangeEvent e) {

                    Double doubleValue = IntegerSpinner.this.getDoubleValue();

                    if (doubleValue != oldValue) {
                        double oldValueCopy = oldValue;

                        oldValue = doubleValue;
                        if (minIsZero && (doubleValue < 0.0)) {
                            doubleValue = 0.0;
                            field.setValue(doubleValue);
                        }

                        notifyListeners(oldValueCopy, doubleValue);
                    }
                }
            });
}
 
Example 11
Source Project: sldeditor   Source File: DecimalSpinner.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates the ui.
 *
 * @param initialValue the initial value
 * @param min the minimum value
 * @param max the maximum value
 * @param stepSize the step size
 * @param noOfDecimalPlaces the number of decimal places
 */
private void createUI(
        Double initialValue,
        Double min,
        Double max,
        Double stepSize,
        double noOfDecimalPlaces) {
    SpinnerNumberModel model = new SpinnerNumberModel(initialValue, min, max, stepSize);
    setModel(model);

    JSpinner.NumberEditor editor = (JSpinner.NumberEditor) getEditor();
    DecimalFormat format = editor.getFormat();
    format.setMinimumFractionDigits((int) noOfDecimalPlaces);

    final JFormattedTextField field = editor.getTextField();
    DefaultFormatter formatter = (DefaultFormatter) field.getFormatter();
    formatter.setCommitsOnValidEdit(true);
    addChangeListener(
            new ChangeListener() {
                private double oldValue = Double.MAX_VALUE;

                @Override
                public void stateChanged(ChangeEvent e) {

                    Double doubleValue = DecimalSpinner.this.getDoubleValue();

                    if (doubleValue != oldValue) {
                        double oldValueCopy = oldValue;

                        oldValue = doubleValue;
                        if (minIsZero && (doubleValue < 0.0)) {
                            doubleValue = 0.0;
                            field.setValue(doubleValue);
                        }

                        notifyListeners(oldValueCopy, doubleValue);
                    }
                }
            });
}
 
Example 12
Source Project: darklaf   Source File: DarkTableCellEditor.java    License: MIT License 4 votes vote down vote up
public DarkTableCellEditor(final JSpinner spinner) {
    super(dummyCheckBox);
    editorComponent = spinner;
    spinner.putClientProperty(SpinnerConstants.KEY_IS_TABLE_EDITOR, Boolean.TRUE);
    setClickCountToStart(2);
    delegate = new EditorDelegate() {
        public Object getCellEditorValue() {
            return spinner.getValue();
        }

        public void setValue(final Object value) {
            try {
                SpinnerModel model = spinner.getModel();
                if (model instanceof SpinnerNumberModel && !(value instanceof Number)) {
                    spinner.setValue(NumberFormat.getInstance().parse(value.toString()));
                } else if (model instanceof SpinnerDateModel && !(value instanceof Date)) {
                    spinner.setValue(DateFormat.getInstance().parse(value.toString()));
                } else {
                    spinner.setValue(value);
                }
                if (spinner.getValue() != null) {
                    Component editor = spinner.getEditor();
                    if (editor instanceof JSpinner.DefaultEditor) {
                        JSpinner.DefaultEditor defaultEditor = ((JSpinner.DefaultEditor) editor);
                        JFormattedTextField.AbstractFormatter formatter = defaultEditor.getTextField()
                                                                                       .getFormatter();
                        if (formatter instanceof DefaultFormatter) {
                            ((DefaultFormatter) formatter).setValueClass(spinner.getValue().getClass());
                        }
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        public boolean shouldSelectCell(final EventObject anEvent) {
            if (anEvent instanceof MouseEvent) {
                MouseEvent e = (MouseEvent) anEvent;
                return e.getID() != MouseEvent.MOUSE_DRAGGED;
            }
            return true;
        }
    };
    setClickCountToStart(2);
}
 
Example 13
private static void testDefaultFormatter() {
    testDefaultFormatter(new DefaultFormatter() {
    });
    testDefaultFormatter(new DefaultFormatter());
}