/** * Selects the passed in field, returning true if it is found, false * otherwise. */ private boolean select(JFormattedTextField ftf, AttributedCharacterIterator iterator, DateFormat.Field field) { int max = ftf.getDocument().getLength(); iterator.first(); do { Map<Attribute, Object> attrs = iterator.getAttributes(); if( attrs != null && attrs.containsKey(field) ) { int start = iterator.getRunStart(field); int end = iterator.getRunLimit(field); if( start != -1 && end != -1 && start <= max && end <= max ) { ftf.select(start, end); } return true; } } while( iterator.next() != CharacterIterator.DONE ); return false; }
public static void Limpar_Campos_Tela(JPanel tela) { for (Component componente : tela.getComponents()) { if (componente instanceof JPanel) { Limpar_Campos_Tela((JPanel) componente); } if (componente instanceof JTextField) { ((JTextField) componente).setText(""); } if (componente instanceof JFormattedTextField) { ((JFormattedTextField) componente).setText(""); } if(componente instanceof JScrollPane){ JViewport viewport = ((JScrollPane)componente).getViewport(); JTable table = (JTable)viewport.getView(); DefaultTableModel model = (DefaultTableModel) table.getModel(); model.getDataVector().removeAllElements(); model.fireTableDataChanged(); } } }
public Object getCellEditorValue() { JFormattedTextField ftf = (JFormattedTextField) getComponent(); Object o = ftf.getValue(); if (o instanceof Integer) { return o; } else if (o instanceof Number) { return new Integer(((Number) o).intValue()); } else { if (DEBUG) { System.out.println("getCellEditorValue: o isn't a Number"); } try { return integerFormat.parseObject(o.toString()); } catch (ParseException exc) { System.err.println("getCellEditorValue: can't parse o: " + o); return null; } } }
private void destacarCampo(JFormattedTextField field) { final int timerDelay = 500; final int totalTime = 2000; final int totalCount = totalTime / timerDelay; Timer timer = new Timer(timerDelay, new ActionListener(){ int count = 0; public void actionPerformed(ActionEvent evt) { if (count % 2 == 0) { field.setBorder(new LineBorder(Color.RED, 2, true)); field.requestFocus(); } else { field.setBorder(new LineBorder(Color.GRAY, 1, false)); if (count >= totalCount) { ((Timer)evt.getSource()).stop(); } } count++; } }); timer.start(); }
@Override public boolean stopCellEditing() { JFormattedTextField ftf = (JFormattedTextField) getComponent(); if (ftf.isEditValid()) { try { ftf.commitEdit(); } catch (java.text.ParseException ex) { } } else { //text is invalid Toolkit.getDefaultToolkit().beep(); textField.selectAll(); return false; //don't let the editor go away } return super.stopCellEditing(); }
@Override public Object getCellEditorValue() { JFormattedTextField ftf = (JFormattedTextField) getComponent(); Object o = ftf.getValue(); if (o instanceof Integer) { return o; } else if (o instanceof Number) { return new Integer(((Number) o).intValue()); } else { try { return integerFormat.parseObject(o.toString()); } catch (ParseException ex) { LOGGER.log(Level.FINE, "getCellEditorValue: can't parse {0}", o); return null; } } }
@Override public Object getCellEditorValue() { JFormattedTextField ftf = (JFormattedTextField) getComponent(); Object o = ftf.getValue(); if (o instanceof Double) { return o; } else if (o instanceof Number) { return new Double(((Number) o).doubleValue()); } else { try { return doubleFormat.parseObject(o.toString()); } catch (ParseException ex) { LOGGER.log(Level.FINE, "getCellEditorValue: can't parse {0}", o); return null; } } }
/** * Creates the {@link JPanel} showing the mission time. * * @param maxwidth * the dimension of the longest label * @return the JPanel showing the mission time */ private JPanel createMtPanel(Dimension maxwidth) { Double mtVal = inverse.evaluate(reliabilityFunction, standardMT); JLabel pmtLabel = new JLabel("P[MT] ="); pmtLabel.setMinimumSize(maxwidth); JLabel mtLabel = new JLabel("MT:"); mtLabel.setMinimumSize(maxwidth); mtProbability = new JFormattedTextField(mtFieldFormat); mtProbability.addActionListener(MeasurePanel.this); mtProbability.setPreferredSize(new Dimension(70, 15)); mtProbability.setHorizontalAlignment(SwingConstants.RIGHT); mtProbability.setText(standardMT.toString()); mt = new JLabel(mtVal.toString()); return createSubPanel("Mission-Time", pmtLabel, mtProbability, mtLabel, mt); }
private void initializeTextFields() { DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator('.'); NumberFormat format = new DecimalFormat("0.00", symbols); format.setMaximumFractionDigits(2); NumberFormatter formatter = new NumberFormatter(format); formatter.setMinimum(0.0); formatter.setMaximum(10000000.0); formatter.setAllowsInvalid(false); this.txtPeso = new JFormattedTextField(formatter); this.txtPeso.setValue(0.0); GridBagConstraints gbc_textField = new GridBagConstraints(); gbc_textField.gridwidth = 10; gbc_textField.insets = new Insets(0, 0, 5, 0); gbc_textField.fill = GridBagConstraints.BOTH; gbc_textField.gridx = 2; gbc_textField.gridy = 10; this.panelSecond.add(this.txtPeso, gbc_textField); this.txtPeso.setColumns(10); }
/** * Returns the calendarField under the start of the selection, or -1 if * there is no valid calendar field under the selection (or the spinner * isn't editing dates. */ private int getCalendarField(JSpinner spinner) { JComponent editor = spinner.getEditor(); if( editor instanceof JSpinner.DateEditor ) { JSpinner.DateEditor dateEditor = (JSpinner.DateEditor) editor; JFormattedTextField ftf = dateEditor.getTextField(); int start = ftf.getSelectionStart(); JFormattedTextField.AbstractFormatter formatter = ftf.getFormatter(); if( formatter instanceof InternationalFormatter ) { Format.Field[] fields = ((InternationalFormatter) formatter).getFields(start); for( int counter = 0; counter < fields.length; counter++ ) { if( fields[counter] instanceof DateFormat.Field ) { int calendarField; if( fields[counter] == DateFormat.Field.HOUR1 ) { calendarField = Calendar.HOUR; } else { calendarField = ((DateFormat.Field) fields[counter]).getCalendarField(); } if( calendarField != -1 ) { return calendarField; } } } } } return -1; }
/** * Returns either the default formatter, display formatter, editor * formatter or null formatter based on the state of the * JFormattedTextField. * * @param source JFormattedTextField requesting * JFormattedTextField.AbstractFormatter * @return JFormattedTextField.AbstractFormatter to handle * formatting duties. */ public JFormattedTextField.AbstractFormatter getFormatter( JFormattedTextField source) { JFormattedTextField.AbstractFormatter format = null; if (source == null) { return null; } Object value = source.getValue(); if (value == null) { format = getNullFormatter(); } if (format == null) { if (source.hasFocus()) { format = getEditFormatter(); } else { format = getDisplayFormatter(); } if (format == null) { format = getDefaultFormatter(); } } return format; }
public SingleIntegerFieldOptionsPanel(String labelString, final InspectionProfileEntry owner, @NonNls final String property, int integerFieldColumns) { super(new GridBagLayout()); final JLabel label = new JLabel(labelString); final JFormattedTextField valueField = createIntegerFieldTrackingValue(owner, property, integerFieldColumns); final GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.insets.right = UIUtil.DEFAULT_HGAP; constraints.weightx = 0.0; constraints.anchor = GridBagConstraints.BASELINE_LEADING; constraints.fill = GridBagConstraints.NONE; add(label, constraints); constraints.gridx = 1; constraints.gridy = 0; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.insets.right = 0; constraints.anchor = GridBagConstraints.BASELINE_LEADING; constraints.fill = GridBagConstraints.NONE; add(valueField, constraints); }
@Override public Object stringToValue (String string) throws ParseException { try { JFormattedTextField ftf = getFormattedTextField(); Object value = ftf.getValue(); if (value instanceof Integer) { return Integer.valueOf(string, 16); } else if (value instanceof Long) { return Long.valueOf(string, 16); } else { throw new IllegalArgumentException( "Illegal Number class for HexaFormatter " + value.getClass()); } } catch (NumberFormatException ex) { throw new ParseException(string, 0); } }
/** * Workaround for a swing bug : when the user enters an illegal value, the * text is forced to the last value. * * @param spinner the spinner to update */ public static void fixIntegerList (final JSpinner spinner) { JSpinner.DefaultEditor editor; editor = (JSpinner.DefaultEditor) spinner.getEditor(); final JFormattedTextField ftf = editor.getTextField(); ftf.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enterAction"); ftf.getActionMap().put( "enterAction", new AbstractAction() { @Override public void actionPerformed (ActionEvent e) { try { spinner.setValue(Integer.parseInt(ftf.getText())); } catch (Exception ex) { // Reset to last value ftf.setText(ftf.getValue().toString()); } } }); }
/** * 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 } } }); }
/** * Construct a <code>JSpinner</code> editor that supports displaying and * editing the value of a <code>SpinnerIntModel</code> with a * <code>JFormattedTextField</code>. <code>This</code> * <code>IntegerEditor</code> becomes both a <code>ChangeListener</code> * on the spinner and a <code>PropertyChangeListener</code> on the new * <code>JFormattedTextField</code>. * * @param spinner the spinner whose model <code>this</code> editor will * monitor * @param format the <code>NumberFormat</code> object that's used to * display and parse the value of the text field. * @exception IllegalArgumentException if the spinners model is not an * instance of <code>SpinnerIntModel</code> * * @see #getTextField * @see SpinnerIntModel * @see java.text.DecimalFormat */ private IntegerEditor(JSpinner spinner, NumberFormat format) { super(spinner); if (!(spinner.getModel() instanceof SpinnerIntModel)) { throw new IllegalArgumentException("model not a SpinnerIntModel"); } format.setGroupingUsed(false); format.setMaximumFractionDigits(0); SpinnerIntModel model = (SpinnerIntModel) spinner.getModel(); NumberFormatter formatter = new IntegerEditorFormatter(model, format); DefaultFormatterFactory factory = new DefaultFormatterFactory(formatter); JFormattedTextField ftf = getTextField(); ftf.setEditable(true); ftf.setFormatterFactory(factory); ftf.setHorizontalAlignment(JTextField.RIGHT); try { String minString = formatter.valueToString(model.getMinimum()); String maxString = formatter.valueToString(model.getMaximum()); // Trying to approximate the width difference between "m" and "0" by multiplying with 0.7 ftf.setColumns((int) Math.round(0.7 * Math.max(maxString.length(), minString.length()))); } catch (ParseException e) { // Nothing to do, the component width will simply be the default } }
private JPanel setupPosBox(String coord, JFormattedTextField field) { JPanel posPanel = new JPanel(); JLabel label = new JLabel(coord); posPanel.add(label); posPanel.add(field); field.addPropertyChangeListener("value", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { update(); } }); return posPanel; }
private JPanel setupSwivelParam(String id, JFormattedTextField field) { JPanel posPanel = new JPanel(); JLabel label = new JLabel(id); posPanel.add(label); posPanel.add(field); field.addPropertyChangeListener("value", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { update(); } }); return posPanel; }
private static JComponent createSpinner(final ConfigAttribute attribute) { final JSpinner spinner = new JSpinner(createModel(attribute)); JSpinner.NumberEditor editor = new JSpinner.NumberEditor(spinner); editor.getTextField().setHorizontalAlignment(JFormattedTextField.LEFT); editor.getFormat().setGroupingUsed(false); spinner.setEditor(editor); spinner.setValue(attribute.getValue()); spinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { attribute.setValue(parseAs(unwrap(attribute.getType()), String.valueOf(spinner.getValue()))); } }); return spinner; }
private JPanel getImageSizePanel() { JPanel imageSizePanel = new JPanel(); imageSizePanel.setLayout(new GridLayout(1, 4)); NumberFormat format = NumberFormat.getInstance(); format.setGroupingUsed(false); NumberFormatter formatter = new NumberFormatter(format); formatter.setValueClass(Integer.class); formatter.setMinimum(0); formatter.setMaximum(Integer.MAX_VALUE); formatter.setCommitsOnValidEdit(true); widthTF = new JFormattedTextField(formatter); widthTF.setValue(1200); widthTF.addFocusListener(FOCUS_LISTENER); heightTF = new JFormattedTextField(formatter); heightTF.setValue(1000); heightTF.addFocusListener(FOCUS_LISTENER); imageSizePanel.add(new JLabel(" Width:")); imageSizePanel.add(widthTF); imageSizePanel.add(new JLabel(" Height:")); imageSizePanel.add(heightTF); return imageSizePanel; }
/** * Returns the appropriate formatter based on the state of * <code>tf</code>. If <code>tf<code> is null we return null, otherwise * we return one of the following: * 1. Returns <code>nullFormatter</code> if <code>tf.getValue()</code> is * null and <code>nullFormatter</code> is not. * 2. Returns <code>editFormatter</code> if <code>tf.hasFocus()</code> is * true and <code>editFormatter</code> is not null. * 3. Returns <code>displayFormatter</code> if <code>tf.hasFocus()</code> is * false and <code>displayFormatter</code> is not null. * 4. Otherwise returns <code>defaultFormatter</code>. */ public AbstractFormatter getFormatter(JFormattedTextField tf) { if (tf == null) return null; if (tf.getValue() == null && nullFormatter != null) return nullFormatter; if (tf.hasFocus() && editFormatter != null) return editFormatter; if (!tf.hasFocus() && displayFormatter != null) return displayFormatter; return defaultFormatter; }
private JPanel getImageSizePanel() { JPanel imageSizePanel = new JPanel(); imageSizePanel.setLayout(new GridLayout(1, 4)); NumberFormat format = NumberFormat.getInstance(); format.setGroupingUsed(false); NumberFormatter formatter = new NumberFormatter(format); formatter.setValueClass(Integer.class); formatter.setMinimum(0); formatter.setMaximum(Integer.MAX_VALUE); formatter.setCommitsOnValidEdit(true); widthTF = new JFormattedTextField(formatter); widthTF.setValue(1200); addFocusListener(widthTF); heightTF = new JFormattedTextField(formatter); heightTF.setValue(1000); addFocusListener(heightTF); imageSizePanel.add(new JLabel(" Width:")); imageSizePanel.add(widthTF); imageSizePanel.add(new JLabel(" Height:")); imageSizePanel.add(heightTF); return imageSizePanel; }
public JFormattedTextField.AbstractFormatter getFormatter( JFormattedTextField source) { JFormattedTextField.AbstractFormatter format = null; if (source == null) { return null; } Object value = source.getValue(); if (value == null) { format = getNullFormatter(); } if (format == null) { if (source.hasFocus()) { format = getEditFormatter(); } else { format = getDisplayFormatter(); } if (format == null) { format = getDefaultFormatter(); } } return format; }
public GridEditPanel(int rasterSize) { JLabel lblSize = new JLabel("size (px)"); lblSize.setFont(Program.TEXT_FONT.deriveFont(Font.BOLD).deriveFont(10f)); textField = new JFormattedTextField(NumberFormat.getIntegerInstance()); textField.setText("16"); textField.setFont(Program.TEXT_FONT.deriveFont(10f)); textField.setColumns(10); textField.setValue(rasterSize); GroupLayout groupLayout = new GroupLayout(this); groupLayout.setHorizontalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addContainerGap() .addComponent(lblSize, GroupLayout.PREFERRED_SIZE, 44, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(textField, GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE) .addGap(34))); groupLayout.setVerticalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addContainerGap() .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE) .addComponent(lblSize, GroupLayout.PREFERRED_SIZE, 13, GroupLayout.PREFERRED_SIZE) .addComponent(textField, GroupLayout.PREFERRED_SIZE, 19, GroupLayout.PREFERRED_SIZE)) .addContainerGap(46, Short.MAX_VALUE))); setLayout(groupLayout); }
@Override public void actionPerformed(ActionEvent e) { WindowFactory.modal().interceptClose(() -> true).onClose((evt) -> updateRenderingOptions()).create((panel) -> { fieldWindowLevel = new JFormattedTextField(new DecimalFormat("#0")); fieldWindowLevel.setValue(VISNode.get().getModel().getUserPreferences().getRenderingOptions().getDicomWindowLevel()); fieldWindowWidth = new JFormattedTextField(new DecimalFormat("#0")); fieldWindowWidth.setValue(VISNode.get().getModel().getUserPreferences().getRenderingOptions().getDicomWindowWidth()); panel.setLayout(new GridLayout(0, 2, 5, 0)); panel.add(new JLabel("Window level", JLabel.RIGHT)); panel.add(fieldWindowLevel); panel.add(new JLabel("Window width", JLabel.RIGHT)); panel.add(fieldWindowWidth); }).setVisible(true); }
/** * Creates a new integer editor */ public IntegerEditor() { super(); setLayout(new BorderLayout()); field = new JFormattedTextField(new DecimalFormat("#0")); add(field); setValue(0); }
/** * Creates a new threshold editor */ public DoubleEditor() { super(); setLayout(new BorderLayout()); field = new JFormattedTextField(new DecimalFormat("#0.0####")); add(field); setValue(0d); }
public static void Limpar_Campos_Tela(JPanel tela, Boolean bloquear_Componentes){ for (Component componente : tela.getComponents()) { if (componente instanceof JPanel) { Limpar_Campos_Tela((JPanel) componente,bloquear_Componentes); } if(componente instanceof JScrollPane){ JViewport viewport = ((JScrollPane)componente).getViewport(); JTable table = (JTable)viewport.getView(); DefaultTableModel model = (DefaultTableModel) table.getModel(); model.getDataVector().removeAllElements(); model.fireTableDataChanged(); table.setEnabled(!bloquear_Componentes); } if (componente instanceof JTextField) { ((JTextField) componente).setText(""); ((JTextField) componente).setEnabled(!bloquear_Componentes); } if (componente instanceof JFormattedTextField) { ((JFormattedTextField) componente).setText(""); ((JFormattedTextField) componente).setEnabled(!bloquear_Componentes); } if(componente instanceof JButton){ ((JButton) componente).setEnabled(!bloquear_Componentes); } } }
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) { } } }); }
public boolean stopCellEditing() { JFormattedTextField ftf = (JFormattedTextField) getComponent(); if (ftf.isEditValid()) { try { ftf.commitEdit(); } catch (java.text.ParseException exc) { } } else { // text is invalid if (!userSaysRevert()) { // user wants to edit return false; // don't let the editor go away } } return super.stopCellEditing(); }
/** * Constructor. */ public DateCellEditor(DateFormat dateFormat) { super(new JFormattedTextField()); textField = (JFormattedTextField) getComponent(); this.dateFormat = dateFormat; DateFormatter dateFormatter = new DateFormatter(dateFormat); textField.setFormatterFactory(new DefaultFormatterFactory(dateFormatter)); textField.setHorizontalAlignment(JTextField.TRAILING); textField.setFocusLostBehavior(JFormattedTextField.PERSIST); // React when the user presses Enter while the editor is // active. (Tab is handled as specified by // JFormattedTextField's focusLostBehavior property.) textField.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "check"); textField.getActionMap().put("check", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (!textField.isEditValid()) { //The text is invalid. Toolkit.getDefaultToolkit().beep(); textField.selectAll(); } else { try { //The text is valid, textField.commitEdit(); //so use it. textField.postActionEvent(); //stop editing } catch (java.text.ParseException ex) { } } } }); }
@Override public Object getCellEditorValue() { JFormattedTextField ftf = (JFormattedTextField) getComponent(); Object o = ftf.getValue(); if (o instanceof Date) { return o; } else { try { return dateFormat.parseObject(o.toString()); } catch (ParseException ex) { LOGGER.log(Level.FINE, "getCellEditorValue: can't parse {0}", o); return null; } } }
@Override public Object getCellEditorValue() { JFormattedTextField ftf = (JFormattedTextField) getComponent(); Object o = ftf.getValue(); if (o instanceof int[]) { return o; } else { LOGGER.log(Level.FINE, "getCellEditorValue: can't parse {0}", o); return null; } }