Example usage for javax.swing.text MaskFormatter MaskFormatter

List of usage examples for javax.swing.text MaskFormatter MaskFormatter

Introduction

In this page you can find the example usage for javax.swing.text MaskFormatter MaskFormatter.

Prototype

public MaskFormatter(String mask) throws ParseException 

Source Link

Document

Creates a MaskFormatter with the specified mask.

Usage

From source file:Main.java

public Main() {
    JFormattedTextField formattedField = null;
    try {/*from w w w.  j  a  v a  2  s.c  o m*/
        MaskFormatter dateMask = new MaskFormatter("##/##/####");
        formattedField = new JFormattedTextField(dateMask);
    } catch (ParseException ex) {
        System.out.println(ex);
    }
    formattedField.setColumns(10);
    formattedField.setInputVerifier(getInputVerifier());

    JTextField field = new JTextField(10);
    format.setLenient(false);

    Box box = Box.createVerticalBox();
    box.add(formattedField);
    box.add(Box.createVerticalStrut(10));
    box.add(field);
    box.setBorder(new EmptyBorder(10, 10, 10, 10));

    JFrame frame = new JFrame();
    frame.add(box);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

From source file:Main.java

MaskFormatter createFormatter(String format) {
    MaskFormatter formatter = null;
    try {// ww  w  .ja  v a2  s . c om
        formatter = new MaskFormatter(format);
        formatter.setPlaceholderCharacter('.'/*or '0' etc*/);
        formatter.setAllowsInvalid(false); // if needed
        formatter.setOverwriteMode(true); // if needed
    } catch (java.text.ParseException exc) {
        System.err.println("formatter is bad: " + exc.getMessage());
    }
    return formatter;
}

From source file:Main.java

private void initComponents() {
    JFrame frame = new JFrame("JFormattedTextField Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    MaskFormatter mask = null;/*from   w  w w .j  a  v a2 s.c  om*/
    try {
        mask = new MaskFormatter("##h##min##s");// the # is for numeric values
        mask.setPlaceholderCharacter('#');
    } catch (ParseException e) {
        e.printStackTrace();
    }
    final JFormattedTextField timeField = new JFormattedTextField(mask);

    // ActionListener for when enter is pressed
    timeField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            Object source = ae.getSource();
            if (source == timeField) {
                // parse to a valid time here
                System.out.println(timeField.getText());
            }
        }
    });
    frame.add(timeField);
    frame.pack();
    frame.setVisible(true);
}

From source file:Main.java

private MaskFormatter createFormatter(String s) {
    MaskFormatter formatter = null;
    try {/* w w  w.  j  a va2 s  . c o m*/
        formatter = new MaskFormatter(s);
    } catch (java.text.ParseException exc) {
        System.err.println("formatter is bad: " + exc.getMessage());
    }
    return formatter;
}

From source file:FactoryDemo.java

public static JPanel demo2() {
    // Demo 2: Change the format of a field when the user presses a button.
    // We can't call field.setFormatter() because that's a protected method.
    // (Plus it wouldn't work anyway. The old factory would replace our new
    // formatter with an "old" one next time the field gains or loses
    // focus.)//  ww w.  ja v a2 s  .  co  m
    // The thing to do is send a new factory to field.setFormatterFactory().

    JPanel pan = new JPanel(new BorderLayout());
    pan.setBorder(new TitledBorder("Demo 2: change format midstream"));

    MaskFormatter lowercase = null;
    try {
        lowercase = new MaskFormatter("LLLL");
    } catch (ParseException pe) {
    }
    final JFormattedTextField field = new JFormattedTextField(lowercase);
    field.setValue("Fore");
    pan.add(field, BorderLayout.CENTER);

    final JButton change = new JButton("change format");
    JPanel changePanel = new JPanel();
    changePanel.add(change);
    pan.add(changePanel, BorderLayout.SOUTH);

    change.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            try {
                field.commitEdit(); // commit current edit (if any)
                MaskFormatter uppercase = new MaskFormatter("UUUU");
                DefaultFormatterFactory factory = new DefaultFormatterFactory(uppercase);
                field.setFormatterFactory(factory);
                change.setEnabled(false);
            } catch (ParseException pe) {
            }
        }
    });

    return pan;
}

From source file:br.com.pontocontrol.controleponto.util.SwingUtils.java

public static void setMask(JFormattedTextField field, String mask) {
    try {/*from  w w w  . j  a  v  a 2s  .  c  om*/
        MaskFormatter maskFormatter = new MaskFormatter(mask);
        maskFormatter.setPlaceholder("");
        maskFormatter.install(field);
    } catch (ParseException ex) {
        LOG.log(Level.SEVERE, "Erro ao definir mscara no campo", ex);
    }
}

From source file:Main.java

protected JFormattedTextField createField() {
    MaskFormatter formatter = null;
    try {/*  w  w  w  .ja  va2s.  c  om*/
        formatter = new MaskFormatter("########");
    } catch (ParseException e) {
        e.printStackTrace(System.out);
    }
    JFormattedTextField jtf = new JFormattedTextField(formatter);
    return jtf;
}

From source file:com.docdoku.core.util.Tools.java

public static String increaseId(String id, String mask) throws ParseException {
    LOGGER.info("#### Tools.increaseId id = " + id + " , mask = " + mask);
    MaskFormatter formatter = new MaskFormatter(mask);
    formatter.setValueContainsLiteralCharacters(false);
    String value = formatter.stringToValue(id).toString();
    StringBuilder newValue = new StringBuilder();
    boolean increase = true;
    for (int i = value.length() - 1; i >= 0; i--) {
        char c = value.charAt(i);
        switch (c) {
        case '9':
            newValue.append((increase) ? '0' : '9');
            break;

        case '8':
            newValue.append((increase) ? '9' : '8');
            increase = false;/*from   w w  w. ja  va  2  s  .  c  o  m*/
            break;

        case '7':
            newValue.append((increase) ? '8' : '7');
            increase = false;
            break;

        case '6':
            newValue.append((increase) ? '7' : '6');
            increase = false;
            break;

        case '5':
            newValue.append((increase) ? '6' : '5');
            increase = false;
            break;

        case '4':
            newValue.append((increase) ? '5' : '4');
            increase = false;
            break;

        case '3':
            newValue.append((increase) ? '4' : '3');
            increase = false;
            break;

        case '2':
            newValue.append((increase) ? '3' : '2');
            increase = false;
            break;

        case '1':
            newValue.append((increase) ? '2' : '1');
            increase = false;
            break;

        case '0':
            newValue.append((increase) ? '1' : '0');
            increase = false;
            break;

        default:
            newValue.append(c);
            break;
        }
    }
    return formatter.valueToString(newValue.reverse().toString());
}

From source file:com.unicorn.co226.ui.patient.AddStudentForm.java

/**
 * Creates new form AddStudentForm/*from w  ww.j  a  va 2  s. c o  m*/
 */
public AddStudentForm(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(WaitingList.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        Logger.getLogger(WaitingList.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(WaitingList.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnsupportedLookAndFeelException ex) {
        Logger.getLogger(WaitingList.class.getName()).log(Level.SEVERE, null, ex);
    }
    this.parent = parent;
    dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    initComponents();
    setLocationRelativeTo(parent);
    medicalPhotos = new File[] {};
    maskFormatterMap = new HashMap<>();

    try {
        maskFormatterMap.put("ENG", new MaskFormatter("E-##-###"));
        MaskFormatter maskFormatter = new MaskFormatter("A-##-###");
        maskFormatter.setValidCharacters("A");
        maskFormatterMap.put("ART", maskFormatter);
        maskFormatterMap.put("SCI", new MaskFormatter("S-##-###"));
        maskFormatterMap.put("MED", new MaskFormatter("M-##-###"));
        maskFormatterMap.put("AHS", new MaskFormatter("AHS-##-###"));
        maskFormatterMap.put("MGT", new MaskFormatter("MGT-##-###"));
        maskFormatterMap.put("VET", new MaskFormatter("V-##-###"));
        maskFormatterMap.put("AGR", new MaskFormatter("AG-##-###"));
        maskFormatterMap.put("DEN", new MaskFormatter("D-##-###"));

    } catch (ParseException ex) {
        Logger.getLogger(AddStudentForm.class.getName()).log(Level.SEVERE, null, ex);
    }
    //dobDatePicker.setDate(new Date(90, 1, 1));
    dobDatePicker.setFormats(dateFormat, new SimpleDateFormat("yyyy"), new SimpleDateFormat("yyyy/MM/dd"));

    fileChooser = new JFileChooser();
    fileChooser.setMultiSelectionEnabled(true);
    fileChooser.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "png"));

    try {
        String nextId = IdGen.getNextId("Patient", "id", "P");
        idTextField.setText(nextId);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(AddStudentForm.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(AddStudentForm.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:view.transacao.Relatorio.java

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.// w w w  . jav  a  2s .c om
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

    buttonGroup1 = new javax.swing.ButtonGroup();
    jButton1 = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jComboBox1 = new javax.swing.JComboBox();
    jButton2 = new javax.swing.JButton();
    jCheckBoxDespesa = new javax.swing.JCheckBox();
    jCheckBoxProvento = new javax.swing.JCheckBox();
    jButton3 = new javax.swing.JButton();
    try {
        MaskFormatter mask = new MaskFormatter("##/##/####");
        dataInicial = new javax.swing.JFormattedTextField(mask);

        dataFinal = new javax.swing.JFormattedTextField(mask);
    } catch (Exception ex) {

    }

    setClosable(true);

    jButton1.setText("Gerar Lista");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jLabel3.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
    jLabel3.setText("Relatorio");

    jTable1.setBackground(new java.awt.Color(254, 254, 254));
    jTable1.setDefaultRenderer(Object.class, new view.RenderizadorTransacao());
    jTable1.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {

    }, new String[] { "ID", "Despesa/Provento", "Descrio", "Valor", "Categoria", "Recorrencia",
            "Data de inserao" }) {
        boolean[] canEdit = new boolean[] { false, false, false, false, false, false, false };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit[columnIndex];
        }
    });
    jTable1.setFocusable(false);
    jTable1.setRowSelectionAllowed(false);
    jScrollPane2.setViewportView(jTable1);

    jLabel1.setText("Data Inicial:");

    jLabel2.setText("Data Final:");

    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione a Categoria" }));
    jComboBox1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jComboBox1ActionPerformed(evt);
        }
    });

    jButton2.setText("Gerar Grfico");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    jCheckBoxDespesa.setText("Despesa");

    jCheckBoxProvento.setText("Provento");

    jButton3.setText("Gerar Histograma");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                    .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jScrollPane2)
                    .addGroup(layout.createSequentialGroup().addGroup(layout
                            .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addGroup(layout.createSequentialGroup().addComponent(jCheckBoxDespesa)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jCheckBoxProvento).addGap(46, 46, 46)
                                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 148,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 148,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 148,
                                            javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup().addComponent(jLabel1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(dataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 166,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18).addComponent(jLabel2).addGap(6, 6, 6)
                                    .addComponent(dataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, 160,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE,
                                            javax.swing.GroupLayout.DEFAULT_SIZE,
                                            javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGap(0, 238, Short.MAX_VALUE)))
                    .addContainerGap()));
    layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jLabel3).addGap(13, 13, 13)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(dataInicial, javax.swing.GroupLayout.PREFERRED_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(dataFinal, javax.swing.GroupLayout.PREFERRED_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2).addComponent(jComboBox1,
                                    javax.swing.GroupLayout.PREFERRED_SIZE,
                                    javax.swing.GroupLayout.DEFAULT_SIZE,
                                    javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1).addComponent(jButton2).addComponent(jCheckBoxDespesa)
                            .addComponent(jCheckBoxProvento).addComponent(jButton3))
                    .addContainerGap()));

    pack();
}