Hot questions for Using JTextField in jformattedtextfield

Top Java Programmings / JTextField / jformattedtextfield

Question:

I need to mask number when the user is typing so on the user UI, user should see a masked number but on the Java code I should get the entire number including masked char that is what user should see 4545********9632 but on Java code (behind) I should get the entire number including masked char. I have tried MaskFormatter with JFormattedTextField and does not work, it displays the entire number.

try {
     MaskFormatter mask=new MaskFormatter("####********####");
      JFormattedTextField js=new JFormattedTextField();
     mask.install(js);
  } catch (ParseException ex) {
      Logger.getLogger(Masker.class.getName()).log(Level.SEVERE, null, ex);
  }

Answer:

Here is my sudgestion,

class ACustomJEditText extends JTextField{
ArrayList<String> realText=new ArrayList<String>();
String displayText="";

public ACustomJEditText() {
    // TODO Auto-generated constructor stub
    super();
    addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {

            // DELETE TEXT on backspace
            if(e.getKeyCode()==KeyEvent.VK_BACK_SPACE) {
                if(realText!=null && realText.isEmpty()==false) {
                    realText.remove(realText.size()-1);//remove character
                }
                turnRealTextToString();
                //set the display text here
                setText(displayText);
                return;
            }

            //avoid any input if string actually string size is greater than 16
            if(realText.size()==16) {
                setText(displayText);
                return;
            }

            //other keys should now be added to the input for only numbers
            try{
                int input=Integer.parseInt(e.getKeyChar()+"");
                //add int to realtext
                realText.add(input+"");
                //turn real text to ####********#### string
                turnRealTextToString();
                setText(displayText);
            }catch (Exception ex) {
                // Other keys fail.
                setText(displayText);
            }
        }

        private void turnRealTextToString() {
            String result="";
            for(int i=0;i<realText.size();i++) {
                if(i>3 && i<12) {
                    result+="*";
                }else {
                    result+=realText.get(i);
                }

            }
            String realDisplay=realText.toString();
            System.out.println("DISPLAY: "+result+" REAL: "+getRealText());

            //set result to display text
            displayText=result;
            setText(displayText);
        }
    });
}

//get the actual real text
public String getRealText() {
    StringBuilder real=new StringBuilder();
    realText.forEach(text->{
        real.append(text);
    });

    return real.toString();
}

}

Should work like magic.

Question:

I have a JFormattedTextField in my form, and i wish that after entering value when user presses enters it should move to next field. But after my all tries I am failed to do so. To achieve this I have attached an ActionListener to JFormattedTextField but pressing of Enter never trigger event. Why? can anybody help?

public class Test extends javax.swing.JFrame {

    /**
     * Creates new form Test
     */
    public Test() {
        initComponents();
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        ftf = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        ftf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        ftf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ftfActionPerformed(evt);
            }
        });

        jLabel1.setText("JFormattedTextField Action Test");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ftf, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(167, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(ftf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(238, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void ftfActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        JOptionPane.showMessageDialog(this, "Enter Pressed");
    }                                   

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Test().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JFormattedTextField ftf;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

Answer:

You need to add an Action:

Action action = new AbstractAction()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        //preform your action here.
    }
};


ftf.addActionListener( action );

And the action is executed when enter key is pressed.

Question:

private JFormattedTextField floatingText = new JFormattedTextField();

DecimalFormat df = new DecimalFormat();
NumberFormatter dnff = new NumberFormatter(df);
DefaultFormatterFactory factory = new DefaultFormatterFactory(dnff);
floatingText.setFormatterFactory(factory);

It works perfectly when I enter small numbers such as 1.23 but when I enter BigDecimals like 9.99999999 it rounds it off to 10. What can I do so Formatter can accept BigDecimal?


Answer:

You can change the min and max digits to display through methods on DecimalFormat. So:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(20);

There are other methods on there to play around with too.

Question:

I have the following JFormattedTextField

try {
    MaskFormatter CabinNoTextF = new MaskFormatter("###");
    CabinNoTextF.setPlaceholderCharacter(' ');
    CabinNoTextField = new JFormattedTextField(CabinNoTextF);
    centerPanelCabin.add(CabinNoTextField);
    addCabinF.add(centerPanelCabin);
    addCabinF.setVisible(true);
} catch (Exception ex) {
}

CabinNoTextField is formatted to only allow three digits to be inputted within the text field. However, I want it so that the user can also enter a single digit as well. I.e. the user may enter 1,15, or 100. But with the code above, the text field only allows three digits to be entered, if I enter a single digit within the text field, it automatically clears.

How do I allow CabinNoTextField to accept three digits at most, but the text field will accept a single digit and double digits as well.


Answer:

Use a NumberFormat

NumberFormat amountFormat = NumberFormat.getNumberInstance();
amountFormat.setMinimumIntegerDigits(1);
amountFormat.setMaximumIntegerDigits(3);
amountFormat.setMaximumFractionDigits(0);

amountField = new JFormattedTextField(amountFormat);

http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

Question:

In NetBeans I've created a project with many of JTextField's. Now I understand that I should validate it. Is it possible to "cast" text fields to JFormattedTextField's?


Answer:

It is possible to "cast" text fields to JFormattedTextField's?

No it's not. At least not directly. The other way around is possible though, given JFormattedTextField extends from JTextField.

So I must delete all JTexFields and add Formatted fields ?

Not necessarily but it's highly recommended. On the other hand you can let the class' variables declared as JTextField and initialize them as JFormattedTextField through custom code:

Then you can "safely" downcast them as JFormattedTextField later. However I'd like to emphasize one more time that it sounds like a dirty workaround. Also note you won't be able to change the setText(...) code to setValue(...) which is preferred for formatted text fields.

Question:

I have to create a Jtextfield where the user will be made to enter about 30 characters.i have created 15 separate Jtextfields and made user to enter only 2 characters in each Jtextfield.when the user enter two characters in first field it automatically jumps to next field and same continues till it reaches 30 characters.

My question is, is there a better way to create Jtextfield.Instead of creating separate 15 Jtextfields can we create one Jtextfield and divide that to 15 partitions and provide the same flow for entering characters. If this is not a good solution, please help me with a better solution. Thanks in advance

My code

    cmd1=new JLabel("Command");
    cmd1.setBounds(20, 76, 70, 30);
    cmd1.setFont(new Font("serif",Font.BOLD,13));
    commandpanel.add(cmd1);

    cmdtext1=new JTextField();
    cmdtext1.setBounds(80, 80,70,25);
    commandpanel.add(cmdtext1);

    examplelabel=new JLabel("Enter HexaDecimal values (For example : 45,1E) ");
    examplelabel.setBounds(260, 50, 250,25);
    examplelabel.setFont(new Font("serif",Font.PLAIN,12));
    commandpanel.add(examplelabel);


    delete1=new JButton("Delete");
    delete1.setBounds(606, 80, 70, 25);
    commandpanel.add(delete1);


    command11=new JTextField(2);
    command11.setBounds(155,80,25,25);      
    command11.setDocument(new JTextFieldLimit(2));
    command11.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command11.getText().length() == 2)
            {
                command12.requestFocus();
            }

        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command11);

    command12=new JTextField();
    command12.setBounds(180,80,25,25);
    command12.setDocument(new JTextFieldLimit(2));
    command12.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command12.getText().length() == 2)
            {
                command13.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command12);

    command13=new JTextField();
    command13.setBounds(205,80,25,25);
    command13.setDocument(new JTextFieldLimit(2));
    command13.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command13.getText().length() == 2)
            {
                command14.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command13);

    command14=new JTextField();
    command14.setBounds(230,80,25,25);
    command14.setDocument(new JTextFieldLimit(2));
    command14.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command14.getText().length() == 2)
            {
                command15.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command14);

    command15=new JTextField();
    command15.setBounds(255,80,25,25);
    command15.setDocument(new JTextFieldLimit(2));
    command15.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command15.getText().length() == 2)
            {
                command16.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command15);

    command16=new JTextField();
    command16.setBounds(280,80,25,25);
    command16.setDocument(new JTextFieldLimit(2));
    command16.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command16.getText().length() == 2)
            {
                command17.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command16);

    command17=new JTextField();
    command17.setBounds(305,80,25,25);
    command17.setDocument(new JTextFieldLimit(2));
    command17.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command17.getText().length() == 2)
            {
                command18.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command17);

    command18=new JTextField();
    command18.setBounds(330,80,25,25);
    command18.setDocument(new JTextFieldLimit(2));
    command18.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command18.getText().length() == 2)
            {
                command19.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command18);

    command19=new JTextField();
    command19.setBounds(355,80,25,25);
    command19.setDocument(new JTextFieldLimit(2));
    command19.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command19.getText().length() == 2)
            {
                command110.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command19);

    command110=new JTextField();
    command110.setBounds(380,80,25,25);
    command110.setDocument(new JTextFieldLimit(2));
    command110.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command110.getText().length() == 2)
            {
                command111.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command110);

    command111=new JTextField();
    command111.setBounds(405,80,25,25);
    command111.setDocument(new JTextFieldLimit(2));
    command111.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command111.getText().length() == 2)
            {
                command112.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command111);

    command112=new JTextField();
    command112.setBounds(430,80,25,25);
    command112.setDocument(new JTextFieldLimit(2));
    command112.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command112.getText().length() == 2)
            {
                command113.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command112);

    command113=new JTextField();
    command113.setBounds(455,80,25,25);
    command113.setDocument(new JTextFieldLimit(2));
    command113.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command113.getText().length() == 2)
            {
                command114.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command113);

    command114=new JTextField();
    command114.setBounds(480,80,25,25);
    command114.setDocument(new JTextFieldLimit(2));
    command114.addKeyListener(new KeyListener()
    {

        @Override
        public void keyTyped(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            // TODO Auto-generated method stub
            if(command114.getText().length() == 2)
            {
                command115.requestFocus();
            }
        }

        @Override
        public void keyPressed(KeyEvent e) 
        {
            // TODO Auto-generated method stub

        }
    });
    commandpanel.add(command114);

    command115=new JTextField();
    command115.setBounds(505,80,25,25);       
    command115.setDocument(new JTextFieldLimit(2));
    commandpanel.add(command115);

    add1=new JButton("Add");
    add1.setBounds(547, 80,56,25);
    add1.addActionListener(new ActionListener()
    {

        @Override
        public void actionPerformed(ActionEvent e)
        {
            // TODO Auto-generated method stub
         add1();

        }

    });
    commandpanel.add(add1);

Answer:

I think this is what you are looking for. Did not finish it but you get the idea!

import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class JComponentLayout extends JFrame implements KeyListener{
    JLabel cmd1;
    JButton add1;
    JTextField cmdtext1;
    JButton delete1;
    JLabel examplelabel;


    Vector<Component> fields = new Vector<Component>(15);
    JPanel commandpanel = new JPanel(new FlowLayout());
   public static void main(String [] args){
       new JComponentLayout();
   }
   public JComponentLayout(){
  cmd1=new JLabel("Command");
    cmd1.setBounds(20, 76, 70, 30);
    cmd1.setFont(new Font("serif",Font.BOLD,13));
    commandpanel.add(cmd1);

    cmdtext1=new JTextField();
    cmdtext1.setBounds(80, 80,70,25);
    commandpanel.add(cmdtext1);

    examplelabel=new JLabel("Enter HexaDecimal values (For example : 45,1E) ");
    examplelabel.setBounds(260, 50, 250,25);
    examplelabel.setFont(new Font("serif",Font.PLAIN,12));
    commandpanel.add(examplelabel);


    for(int e = 0;  e < 15; ++e){
        JTextField command = new JTextField(2);
        command.addKeyListener(this);
        commandpanel.add(command);
        fields.add(command);
    }


    delete1=new JButton("Delete");
    delete1.setBounds(606, 80, 70, 25);
    commandpanel.add(delete1);


    add1=new JButton("Add");
    add1.setBounds(547, 80,56,25);
    add1.addActionListener(new ActionListener()
    {

        @Override
        public void actionPerformed(ActionEvent e){
            // TODO Auto-generated method stub
        }

    });

    commandpanel.add(add1);
    this.add(commandpanel);
    this.setVisible(true);
   }



    @Override
    public void keyTyped(KeyEvent e) 
    {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyReleased(KeyEvent e){
        JTextField source = (JTextField)e.getSource();

        // TODO Auto-generated method stub
        if(source.getText().length() == 2){
            fields.get((1 + fields.indexOf(source)) 
            % fields.size()).requestFocus();
        }       
    }

    @Override
    public void keyPressed(KeyEvent e) 
    {
        // TODO Auto-generated method stub

    }
}