Example usage for javax.swing JFormattedTextField setValue

List of usage examples for javax.swing JFormattedTextField setValue

Introduction

In this page you can find the example usage for javax.swing JFormattedTextField setValue.

Prototype

@BeanProperty(visualUpdate = true, description = "The value to be formatted.")
public void setValue(Object value) 

Source Link

Document

Sets the value that will be formatted by an AbstractFormatter obtained from the current AbstractFormatterFactory.

Usage

From source file:com.streamhub.StreamHubLicenseGenerator.java

private static JPanel createMacAddressRow() {
    JPanel macAddressPanel = new JPanel(new FlowLayout());

    Calendar yesterday = Calendar.getInstance();
    yesterday.setTime(new Date());
    yesterday.add(Calendar.DAY_OF_MONTH, -1);

    Calendar expiry = Calendar.getInstance();
    expiry.setTime(yesterday.getTime());
    expiry.add(Calendar.DAY_OF_MONTH, 60);

    JLabel macAddressLabel = new JLabel("MAC Address:");
    JTextField macAddress = new JTextField(17);
    JLabel startDateLabel = new JLabel("Start Date");
    final JFormattedTextField startDate = new JFormattedTextField(new SimpleDateFormat(DATE_FORMAT));
    startDate.setValue(yesterday.getTime());

    JLabel expiryDateLabel = new JLabel("Expiry Date");
    final JFormattedTextField expiryDate = new JFormattedTextField(new SimpleDateFormat(DATE_FORMAT));
    expiryDate.setValue(expiry.getTime());

    startDate.addKeyListener(new KeyListener() {
        @Override// w w  w.j av  a  2s. c o  m
        public void keyTyped(KeyEvent arg0) {
            // Get the new date and change expiry to suit
            Date date = (Date) startDate.getValue();
            Calendar tempCal = Calendar.getInstance();
            tempCal.setTime(date);
            tempCal.add(Calendar.DAY_OF_MONTH, 60);
            expiryDate.setValue(tempCal.getTime());
        }

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }
    });

    JComboBox edition = new JComboBox(new String[] { "web", "enterprise" });
    JLabel nameLabel = new JLabel("Name:");
    JTextField name = new JTextField(15);

    JLabel numUsersLabel = new JLabel("Num. Users:");
    JTextField numUsers = new JTextField(DEFAULT_NUM_USERS);

    macAddressPanel.add(macAddressLabel);
    macAddressPanel.add(macAddress);
    macAddressPanel.add(startDateLabel);
    macAddressPanel.add(startDate);
    macAddressPanel.add(expiryDateLabel);
    macAddressPanel.add(expiryDate);
    macAddressPanel.add(edition);
    macAddressPanel.add(nameLabel);
    macAddressPanel.add(name);
    macAddressPanel.add(numUsersLabel);
    macAddressPanel.add(numUsers);
    return macAddressPanel;
}

From source file:FieldValidator.java

private static JComponent createContent() {
    Dimension labelSize = new Dimension(80, 20);

    Box box = Box.createVerticalBox();

    // A single LayerUI for all the fields.
    LayerUI<JFormattedTextField> layerUI = new ValidationLayerUI();

    // Number field.
    JLabel numberLabel = new JLabel("Number:");
    numberLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    numberLabel.setPreferredSize(labelSize);

    NumberFormat numberFormat = NumberFormat.getInstance();
    JFormattedTextField numberField = new JFormattedTextField(numberFormat);
    numberField.setColumns(16);/*from   w  w  w  .j  a va2s .  com*/
    numberField.setFocusLostBehavior(JFormattedTextField.PERSIST);
    numberField.setValue(42);

    JPanel numberPanel = new JPanel();
    numberPanel.add(numberLabel);
    numberPanel.add(new JLayer<JFormattedTextField>(numberField, layerUI));

    // Date field.
    JLabel dateLabel = new JLabel("Date:");
    dateLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    dateLabel.setPreferredSize(labelSize);

    DateFormat dateFormat = DateFormat.getDateInstance();
    JFormattedTextField dateField = new JFormattedTextField(dateFormat);
    dateField.setColumns(16);
    dateField.setFocusLostBehavior(JFormattedTextField.PERSIST);
    dateField.setValue(new java.util.Date());

    JPanel datePanel = new JPanel();
    datePanel.add(dateLabel);
    datePanel.add(new JLayer<JFormattedTextField>(dateField, layerUI));

    // Time field.
    JLabel timeLabel = new JLabel("Time:");
    timeLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    timeLabel.setPreferredSize(labelSize);

    DateFormat timeFormat = DateFormat.getTimeInstance();
    JFormattedTextField timeField = new JFormattedTextField(timeFormat);
    timeField.setColumns(16);
    timeField.setFocusLostBehavior(JFormattedTextField.PERSIST);
    timeField.setValue(new java.util.Date());

    JPanel timePanel = new JPanel();
    timePanel.add(timeLabel);
    timePanel.add(new JLayer<JFormattedTextField>(timeField, layerUI));

    // Put them all in the box.
    box.add(Box.createGlue());
    box.add(numberPanel);
    box.add(Box.createGlue());
    box.add(datePanel);
    box.add(Box.createGlue());
    box.add(timePanel);

    return box;
}

From source file:Main.java

private JFormattedTextField init(JFormattedTextField jtf) {
    jtf.setValue(0);
    jtf.addFocusListener(new FocusAdapter() {
        @Override//w w  w  . j  a  v a 2s .  co  m
        public void focusLost(FocusEvent e) {
            Number v1 = (Number) a.getValue();
            Number v2 = (Number) b.getValue();
            sum.setValue(v1.longValue() + v2.longValue());
        }
    });
    return jtf;
}

From source file:com.jgoodies.validation.tutorial.formatted.NumberExample.java

/**
 * Appends the demo rows to the given builder and returns the List of
 * formatted text fields.//ww  w  .  j ava2  s  .c  om
 * 
 * @param builder  the builder used to add components to
 * @return the List of formatted text fields
 */
private List appendDemoRows(DefaultFormBuilder builder) {
    // The Formatter is choosen by the initial value.
    JFormattedTextField defaultNumberField = new JFormattedTextField(new Long(42));

    // The Formatter is choosen by the given Format.
    JFormattedTextField noInitialValueField = new JFormattedTextField(NumberFormat.getIntegerInstance());

    // Uses a custom NumberFormat.
    NumberFormat customFormat = NumberFormat.getIntegerInstance();
    customFormat.setMinimumIntegerDigits(3);
    JFormattedTextField customFormatField = new JFormattedTextField(new NumberFormatter(customFormat));

    // Uses a custom NumberFormatter that prints natural language strings.
    JFormattedTextField customFormatterField = new JFormattedTextField(new CustomNumberFormatter());

    // Uses a custom FormatterFactory that used different formatters
    // for the display and while editing.
    DefaultFormatterFactory formatterFactory = new DefaultFormatterFactory(new NumberFormatter(),
            new CustomNumberFormatter());
    JFormattedTextField formatterFactoryField = new JFormattedTextField(formatterFactory);

    // Wraps a NumberFormatter to map empty strings to null and vice versa.
    JFormattedTextField numberOrNullField = new JFormattedTextField(new EmptyNumberFormatter());

    // Wraps a NumberFormatter to map empty strings to -1 and vice versa.
    Integer emptyValue = new Integer(-1);
    JFormattedTextField numberOrEmptyValueField = new JFormattedTextField(new EmptyNumberFormatter(emptyValue));
    numberOrEmptyValueField.setValue(emptyValue);

    // Commits values on valid edit texts.
    DefaultFormatter formatter = new NumberFormatter();
    formatter.setCommitsOnValidEdit(true);
    JFormattedTextField commitOnValidEditField = new JFormattedTextField(formatter);

    // Returns number values of type Integer
    NumberFormatter numberFormatter = new NumberFormatter();
    numberFormatter.setValueClass(Integer.class);
    JFormattedTextField integerField = new JFormattedTextField(numberFormatter);

    Format displayFormat = new DisplayFormat(NumberFormat.getIntegerInstance());
    Format typedDisplayFormat = new DisplayFormat(NumberFormat.getIntegerInstance(), true);
    List fields = new LinkedList();
    fields.add(Utils.appendRow(builder, "Default", defaultNumberField, typedDisplayFormat));
    fields.add(Utils.appendRow(builder, "No initial value", noInitialValueField, displayFormat));
    fields.add(Utils.appendRow(builder, "Empty <-> null", numberOrNullField, displayFormat));
    fields.add(Utils.appendRow(builder, "Empty <->   -1", numberOrEmptyValueField, displayFormat));
    fields.add(Utils.appendRow(builder, "Custom format", customFormatField, displayFormat));
    fields.add(Utils.appendRow(builder, "Custom formatter", customFormatterField, displayFormat));
    fields.add(Utils.appendRow(builder, "Formatter factory", formatterFactoryField, displayFormat));
    fields.add(Utils.appendRow(builder, "Commits on valid edit", commitOnValidEditField, displayFormat));
    fields.add(Utils.appendRow(builder, "Integer Result", integerField, typedDisplayFormat));

    return fields;
}

From source file:com.jgoodies.validation.tutorial.formatted.DateExample.java

/**
 * Appends the demo rows to the given builder and returns the List of
 * formatted text fields./*from  w  ww . j  ava2 s.  com*/
 * 
 * @param builder  the builder used to add components to
 * @return the List of formatted text fields
 */
private List appendDemoRows(DefaultFormBuilder builder) {
    // The Formatter is choosen by the initial value.
    JFormattedTextField defaultDateField = new JFormattedTextField(new Date());

    // The Formatter is choosen by the given Format.
    JFormattedTextField noInitialValueField = new JFormattedTextField(DateFormat.getDateInstance());

    // Uses a custom DateFormat.
    DateFormat customFormat = DateFormat.getDateInstance(DateFormat.SHORT);
    JFormattedTextField customFormatField = new JFormattedTextField(new DateFormatter(customFormat));

    // Uses a RelativeDateFormat.
    DateFormat relativeFormat = new RelativeDateFormat();
    JFormattedTextField relativeFormatField = new JFormattedTextField(new DateFormatter(relativeFormat));

    // Uses a custom DateFormatter that allows relative input and
    // prints natural language strings.
    JFormattedTextField relativeFormatterField = new JFormattedTextField(new RelativeDateFormatter());

    // Uses a custom FormatterFactory that used different formatters
    // for the display and while editing.
    DefaultFormatterFactory formatterFactory = new DefaultFormatterFactory(
            new RelativeDateFormatter(false, true), new RelativeDateFormatter(true, true));
    JFormattedTextField relativeFactoryField = new JFormattedTextField(formatterFactory);

    // Wraps a DateFormatter to map empty strings to null and vice versa.
    JFormattedTextField numberOrNullField = new JFormattedTextField(new EmptyDateFormatter());

    // Wraps a DateFormatter to map empty strings to -1 and vice versa.
    Date epoch = new Date(0); // January 1, 1970
    JFormattedTextField numberOrEmptyValueField = new JFormattedTextField(new EmptyDateFormatter(epoch));
    numberOrEmptyValueField.setValue(epoch);

    // Commits value on valid edit text
    DefaultFormatter formatter = new RelativeDateFormatter();
    formatter.setCommitsOnValidEdit(true);
    JFormattedTextField commitOnValidEditField = new JFormattedTextField(formatter);

    // A date field as created by the BasicComponentFactory:
    // Uses relative date input, and maps empty strings to null.
    ValueModel dateHolder = new ValueHolder();
    JFormattedTextField componentFactoryField = ExampleComponentFactory.createDateField(dateHolder);

    Format displayFormat = new DisplayFormat(DateFormat.getDateInstance());
    List fields = new LinkedList();
    fields.add(Utils.appendRow(builder, "Default", defaultDateField, displayFormat));
    fields.add(Utils.appendRow(builder, "No initial value", noInitialValueField, displayFormat));
    fields.add(Utils.appendRow(builder, "Empty <->  null", numberOrNullField, displayFormat));
    fields.add(Utils.appendRow(builder, "Empty <-> epoch", numberOrEmptyValueField, displayFormat));
    fields.add(Utils.appendRow(builder, "Short format", customFormatField, displayFormat));
    fields.add(Utils.appendRow(builder, "Relative format", relativeFormatField, displayFormat));
    fields.add(Utils.appendRow(builder, "Relative formatter", relativeFormatterField, displayFormat));
    fields.add(Utils.appendRow(builder, "Relative factory", relativeFactoryField, displayFormat));
    fields.add(Utils.appendRow(builder, "Commits on valid edit", commitOnValidEditField, displayFormat));
    fields.add(Utils.appendRow(builder, "Relative, maps null", componentFactoryField, displayFormat));

    return fields;
}

From source file:components.IntegerEditor.java

public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
        int column) {
    JFormattedTextField ftf = (JFormattedTextField) super.getTableCellEditorComponent(table, value, isSelected,
            row, column);/*from www . ja v  a2 s  . c  o  m*/
    ftf.setValue(value);
    return ftf;
}

From source file:FormatTest.java

public FormatTestFrame() {
    setTitle("FormatTest");
    setSize(WIDTH, HEIGHT);//from w ww.j a v a  2  s. c  o  m

    JPanel buttonPanel = new JPanel();
    okButton = new JButton("Ok");
    buttonPanel.add(okButton);
    add(buttonPanel, BorderLayout.SOUTH);

    mainPanel = new JPanel();
    mainPanel.setLayout(new GridLayout(0, 3));
    add(mainPanel, BorderLayout.CENTER);

    JFormattedTextField intField = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField.setValue(new Integer(100));
    addRow("Number:", intField);

    JFormattedTextField intField2 = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField2.setValue(new Integer(100));
    intField2.setFocusLostBehavior(JFormattedTextField.COMMIT);
    addRow("Number (Commit behavior):", intField2);

    JFormattedTextField intField3 = new JFormattedTextField(
            new InternationalFormatter(NumberFormat.getIntegerInstance()) {
                protected DocumentFilter getDocumentFilter() {
                    return filter;
                }

                private DocumentFilter filter = new IntFilter();
            });
    intField3.setValue(new Integer(100));
    addRow("Filtered Number", intField3);

    JFormattedTextField intField4 = new JFormattedTextField(NumberFormat.getIntegerInstance());
    intField4.setValue(new Integer(100));
    intField4.setInputVerifier(new FormattedTextFieldVerifier());
    addRow("Verified Number:", intField4);

    JFormattedTextField currencyField = new JFormattedTextField(NumberFormat.getCurrencyInstance());
    currencyField.setValue(new Double(10));
    addRow("Currency:", currencyField);

    JFormattedTextField dateField = new JFormattedTextField(DateFormat.getDateInstance());
    dateField.setValue(new Date());
    addRow("Date (default):", dateField);

    DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT);
    format.setLenient(false);
    JFormattedTextField dateField2 = new JFormattedTextField(format);
    dateField2.setValue(new Date());
    addRow("Date (short, not lenient):", dateField2);

    try {
        DefaultFormatter formatter = new DefaultFormatter();
        formatter.setOverwriteMode(false);
        JFormattedTextField urlField = new JFormattedTextField(formatter);
        urlField.setValue(new URL("http://java.sun.com"));
        addRow("URL:", urlField);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    try {
        MaskFormatter formatter = new MaskFormatter("###-##-####");
        formatter.setPlaceholderCharacter('0');
        JFormattedTextField ssnField = new JFormattedTextField(formatter);
        ssnField.setValue("078-05-1120");
        addRow("SSN Mask:", ssnField);
    } catch (ParseException exception) {
        exception.printStackTrace();
    }

    JFormattedTextField ipField = new JFormattedTextField(new IPAddressFormatter());
    ipField.setValue(new byte[] { (byte) 130, 65, 86, 66 });
    addRow("IP Address:", ipField);
}

From source file:com.anrisoftware.prefdialog.miscswing.filetextfield.FileTextTransferHandler.java

private boolean importFile(TransferSupport support) {
    JFormattedTextField field = (JFormattedTextField) support.getComponent();
    Transferable transferable = support.getTransferable();
    try {/* w  w w  .j a va2s  .c o  m*/
        String string = (String) transferable.getTransferData(stringFlavor);
        File file = new File(stringToURI.convert(string));
        field.setValue(file);
        log.importFile(this, file);
    } catch (UnsupportedFlavorException e) {
    } catch (IOException e) {
        log.errorIO(this, e);
        return false;
    } catch (ConvertException e) {
        log.errorNotValidURISyntax(this, e);
        return false;
    }
    return true;
}

From source file:Main.java

private JFormattedTextField setFormat(JFormattedTextField jft, Locale local1, int minFra, int maxFra) {
    NumberFormat numberFormat;/*from   w ww .j a  v a  2  s  .  c o  m*/
    Locale local = local1;
    int setMin = minFra;
    int setMax = maxFra;
    numberFormat = NumberFormat.getCurrencyInstance(local);
    numberFormat.setMinimumFractionDigits(setMin);
    numberFormat.setMaximumFractionDigits(setMax);
    numberFormat.setRoundingMode(RoundingMode.HALF_UP);
    jft = new JFormattedTextField(numberFormat);
    jft.setValue(new Double(342.796));
    return jft;
}

From source file:com.googlecode.vfsjfilechooser2.accessories.connection.ConnectionDialog.java

private void initListeners() {
    this.portTextField.addKeyListener(new KeyAdapter() {
        @Override// w ww  .  j  a  v  a  2s.  c o  m
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();

            if (!((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
                getToolkit().beep();
                e.consume();
            } else {
                setPortTextFieldDirty(true);
            }
        }
    });

    this.portTextField.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            JFormattedTextField f = (JFormattedTextField) e.getSource();
            String text = f.getText();

            if (text.length() == 0) {
                f.setValue(null);
            }

            try {
                f.commitEdit();
            } catch (ParseException exc) {
            }
        }
    });

    this.cancelButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (currentWorker != null) {
                if (currentWorker.isAlive()) {
                    currentWorker.interrupt();
                    setCursor(Cursor.getDefaultCursor());
                }
            }

            setVisible(false);
        }
    });

    this.connectButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            currentWorker = new Thread() {
                @Override
                public void run() {
                    StringBuilder error = new StringBuilder();
                    FileObject fo = null;

                    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                    try {
                        String m_username = usernameTextField.getText();
                        String m_defaultRemotePath = defaultRemotePathTextField.getText();
                        char[] m_password = passwordTextField.getPassword();
                        String m_hostname = hostnameTextField.getText();
                        String m_protocol = protocolList.getSelectedItem().toString();

                        int m_port = -1;

                        if (portTextField.isEditValid() && (portTextField.getValue() != null)) {
                            String s = portTextField.getValue().toString();
                            m_port = Integer.valueOf(s);
                        }

                        Builder credentialsBuilder = Credentials.newBuilder(m_hostname)
                                .defaultRemotePath(m_defaultRemotePath).username(m_username)
                                .password(m_password).protocol(m_protocol).port(m_port);

                        Credentials credentials = credentialsBuilder.build();

                        String uri = credentials.toFileObjectURL();

                        if (isInterrupted()) {
                            setPortTextFieldDirty(false);

                            return;
                        }

                        fo = VFSUtils.resolveFileObject(uri);

                        if ((fo != null) && !fo.exists()) {
                            fo = null;
                        }
                    } catch (Exception err) {
                        error.append(err.getMessage());
                        setCursor(Cursor.getDefaultCursor());
                    }

                    if ((error.length() > 0) || (fo == null)) {
                        error.delete(0, error.length());
                        error.append("Failed to connect!");
                        error.append("\n");
                        error.append("Please check parameters and try again.");

                        JOptionPane.showMessageDialog(ConnectionDialog.this, error, "Error",
                                JOptionPane.ERROR_MESSAGE);
                        setCursor(Cursor.getDefaultCursor());

                        return;
                    }

                    if (isInterrupted()) {
                        return;
                    }

                    fileChooser.setCurrentDirectoryObject(fo);

                    setCursor(Cursor.getDefaultCursor());

                    resetFields();

                    if (bookmarksDialog != null) {
                        String bTitle = fo.getName().getBaseName();

                        if (bTitle.trim().equals("")) {
                            bTitle = fo.getName().toString();
                        }

                        String bURL = fo.getName().getURI();
                        bookmarksDialog.getBookmarks().add(new TitledURLEntry(bTitle, bURL));
                        bookmarksDialog.getBookmarks().save();
                    }

                    setVisible(false);
                }
            };

            currentWorker.setPriority(Thread.MIN_PRIORITY);
            currentWorker.start();
        }
    });

    // add the usual right click popup menu(copy, paste, etc.)
    PopupHandler.installDefaultMouseListener(hostnameTextField);
    PopupHandler.installDefaultMouseListener(portTextField);
    PopupHandler.installDefaultMouseListener(usernameTextField);
    PopupHandler.installDefaultMouseListener(passwordTextField);
    PopupHandler.installDefaultMouseListener(defaultRemotePathTextField);

    this.protocolList.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                selectPortNumber();
            }
        }
    });

    this.protocolList.setSelectedItem(Protocol.FTP);
}