Hot questions for Using JTextField in netbeans

Question:


Answer:

The first thing we need to do is get the text from a JTextField and store it in a String, like this:

String textFieldVal = yourTextField.getText();

Then, we have to write the value to a text file, like this:

PrintWriter writer = new PrintWriter("textFieldOutput.txt", "UTF-8");
writer.println(textFieldVal);
writer.close();

So, this is what it would look like in your first class:

String textField1Val = jTextField1.getText();
String textField2Val = jTextField2.getText();
String textField3Val = jTextField3.getText();
String textField4Val = jTextField4.getText();
String textField5Val = jTextField5.getText();
String textField6Val = jTextField6.getText();
String textField7Val = jTextField7.getText();

And when you want to save it to a text file:

PrintWriter writer = new PrintWriter("textFieldOutput.txt", "UTF-8");
writer.println("First text field:");
writer.println(textField1Val);
writer.println("Second text field:");
writer.println(textField2Val);
writer.println("Third text field:");
writer.println(textField3Val);
writer.println("Fourth text field:");
writer.println(textField4Val);
writer.println("Fifth text field:");
writer.println(textField5Val);
writer.println("Sixth text field:");
writer.println(textField6Val);
writer.println("Seventh text field:");
writer.println(textField7Val);
writer.close();

However, this will overwrite the file if it already exists, so in your other classes, do this:

try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("textFieldOutput.txt", true)))) {
writer.println(textField1Val);
writer.println(textField2Val);
// etc...
} catch (IOException e) {

}

That way, it will add to the file instead of erasing all the text. I hope this helps!

EDIT:

Here is an example ActionListener referencing a single void with all of the code:

jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveText(evt);
            }
        });

And somewhere else in your class:

private void saveText(evt) {
    String textField1Val = jTextField1.getText();
    String textField2Val = jTextField2.getText();
    String textField3Val = jTextField3.getText();
    String textField4Val = jTextField4.getText();
    String textField5Val = jTextField5.getText();
    String textField6Val = jTextField6.getText();
    String textField7Val = jTextField7.getText();

    PrintWriter writer = new PrintWriter("textFieldOutput.txt", "UTF-8");
    writer.println("First text field:");
    writer.println(textField1Val);
    writer.println("Second text field:");
    writer.println(textField2Val);
    writer.println("Third text field:");
    writer.println(textField3Val);
    writer.println("Fourth text field:");
    writer.println(textField4Val);
    writer.println("Fifth text field:");
    writer.println(textField5Val);
    writer.println("Sixth text field:");
    writer.println(textField6Val);
    writer.println("Seventh text field:");
    writer.println(textField7Val);
    writer.close();
}

Question:

I created a simple application where the user enters two values and automatically updates a textfield with the answer and checks to see if the input is numbers or not.

The code (used from this question: How to Auto Calculate input numeric values of Text Field in JAVA) to check the user input is as follows:

private boolean isDigit(String string) 
{
    for (int n = 0; n < string.length(); n++) 
    {
        //get a single character of the string
        char c = string.charAt(n);

        if (!Character.isDigit(c)) 
        {
            //if its an alphabetic character or white space
            return false;
        }
    }
    return true;
}

It works but when the textfields are blank, the following error message comes up: java.lang.NumberFormatException: For input string: "".

How can I alter the code I have used so that blank textfields are acceptable and do not produce errors?


Answer:

You can just add an if at start to check if the string is legal

private boolean isDigit(String string) 
{
    if(string == null || string.isEmpty()) {
        return false;
    }

    for (int n = 0; n < string.length(); n++) 
    {
        //get a single character of the string
        char c = string.charAt(n);

        if (!Character.isDigit(c)) 
        {
            //if its an alphabetic character or white space
            return false;
        }
    }
    return true;
}

Question:

I have an empty JTextField that the user should modify with an int number. However, even once the JTextFiled has been filled with an integer, when I go to get the String from that JTextField, the string results "" (-> empty). How could I save the new value of the Field? what should I do? Here's the problem:

//Class where JTextField is initialized: 

 javax.swing.JTextField tMax = new javax.swing.JTextField();
 tMax.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tMaxKeyTyped(evt);
            }
        });
private void tMaxKeyTyped(java.awt.event.KeyEvent evt) {                                   
// TODO add your handling code here:
    char c = evt.getKeyChar();
    if(!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || c == KeyEvent.VK_DELETE)) {
        getToolkit().beep();
        evt.consume();
    }
}
public String getTMax() {
    String tMaxString = tMax.getText();
    return tMaxString;
}


//Class where tMax should be used

    //code
   private void runBtnActionPerformed(java.awt.event.ActionEvent evt) {
   Panel class1 = new Panel();
   String tMaxString = class1.getTMax();
   System.out.println(tMaxString);

When I run the program and I click the Run Botton an Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "".

What can I do for saving the modified JTextField? Thank you so much.


Answer:

You have your tMax field defined twice. Once as an instance variable and once as a local variable.

Get rid of the local variable:

//javax.swing.JTextField tMax = new javax.swing.JTextField();
tMax = new javax.swing.JTextField();

even once the JTextFiled has been filled with an integer,

Don't use a KeyListener to edit the text as it is typed. Instead you should be using:

  1. a DocumentFilter
  2. a JFormattedTextField
  3. a JSpinner

Question:

    double B=Double.parseDouble(emp_txt2.getText());
    double C=Double.parseDouble(nopay_txt3.getText());
    double E=Double.parseDouble(wop_txt4.getText());
    double F=Double.parseDouble(wop_txt5.getText());

   double f =B+C+E+F;
   String p = String.format("%.2f",f);
   lb1_total3.setText(p);

I want to assign double B,C,E,F values to zero when the jtextfield is empty.


Answer:

You could use this method instead of Double.parseDouble.

public static double tryParsDouble(String s, double defaultValue) {
     if (s == null) return defaultValue;

     try {
         return Double.parseDouble(s);
     } catch (NumberFormatException x) {
         return defaultValue;
     }  
}

And then to:

double F = tryParsDouble(wop_txt5.getText(), 0.0);

Question:

I want to create a small Netbeans application related to school students. I have two JTextFields. In this JTextFields I want to show some words like "apple", then want to show "mango" etc.

The details are as follows.

  1. When the application is start I want to show in JtextField1 as "apple". When the student type it as same or wrong entry then auto move to next word "mango" in same JTextfield1.

  2. In this application JButton will not be use.


Answer:

I'm guessing that you have two JTextFields, one that the user is not supposed to edit and is for display only -- so make that field non-editable by

  1. calling setFocusable(false) so the JTextField can never receive focus
  2. And if you desire, calling setEditable(false)

In your 2nd JTextField, give it an ActionListener via addActionListener(...) that inside of the listener have the code check the 2nd JTextField's text and if incorrect, change the text in the first JTextField.

firstTextField.setFocusable(false);
firstTextField.setEditable(false);

secondTextField.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        String text = secondTextField.getText();

        // here check the text String and if incorrect
        // call setText(...) on the firstTextField
    }
});

Note that by adding an ActionListener to the JTextField itself, you now have a listener that is activated when the user presses the enter button when this field has focus. No need for a JButton for this to work.

Question:

Not sure if this is even remotely possible, but...

I have a jFrame with 10 different Textfields. Elequently named tf1, tf2, tf3...

What I'd LOVE to do is be able to reference them dynamically. Something like:

int i = 1;

while (i<11) {
    tf[i].settext("blah - " + i);
}

Any ideas? If anybody knows of a working example it'd be great.


Answer:

If you want to set the text of all the textfields in a JFrame:

Component ca[] = getContentPane().getComponents();
System.out.println("ca = " + Arrays.toString(ca));
int i = 0;
for(Component c: ca) {
    if(JTextField.class.isAssignableFrom(c.getClass())) {
        JTextField tf = (JTextField) c;
        tf.setText("blah -"+(++i));
    }
}

Question:

i'm trying to get the selected date from Jdatechooser and display the age corresponding to the date in a Textfield, i saw all the threads discussing this problem but it doesn"t work for me.here is my code:

 private void datenaiss_choozPropertyChange(java.beans.PropertyChangeEvent evt) {                                               
    Date date = (Date) datenaiss_chooz.getDate(); 
LocalDate ld = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
Period p =Period.between(ld, LocalDate.now());
age.setText(p);


}              

Answer:

Solution to your problem using joda-time :

DateTime birthDate = new DateTime(1990, 1, 15, 0, 0, 0, 0);
DateTime now = new DateTime();
Period period = new Period(birthDate, now);
int years = period.getYears();
System.out.println(years);

This will give you the difference you required !

Question:

I want jTextField with 12 0s and I need to change those 0s to numbers I type as I type.

  • In begining there is 000000000000
  • If I type 123 then it should be 000000000123

I done this on KeyPressed event, but it's not working properly.

  try {
        int i = Integer.parseInt(jTextField1.getText());
        jTextField1.setText(String.format("%012d", i));
    } catch (Exception e) {
        jTextField1.setText(String.format("%012d", 0));
    }
}             

It changes as I type, but there is few problems.

  1. It changes till I type 11 numbers, just after I type 12th number it delete all numbers and it display again as 000000000005 (if 12th number I typed is 5)
  2. When I delete all it shows only 10 0s not 12,but When I type a number again it shows typed number and 11 0s.

Any solutions?


Answer:

Here is a custom class that tries to simulate data entry of a bank machine. That is text is entered right to left:

import java.awt.*;
import java.text.*;
import javax.swing.*;
import javax.swing.text.*;

public class ABMTextField extends JTextField
{
    private DecimalFormat format;
    private String decimal;

    public ABMTextField(DecimalFormat format)
    {
        this.format = format;

        decimal = Character.toString( format.getDecimalFormatSymbols().getDecimalSeparator() );

        setColumns( format.toPattern().length() );
        setHorizontalAlignment(JFormattedTextField.TRAILING);

        setText( format.format(0.0) );

        AbstractDocument doc = (AbstractDocument)getDocument();
        doc.setDocumentFilter( new ABMFilter() );
    }

    @Override
    public void setText(String text)
    {
        Number number = format.parse(text, new ParsePosition(0));

        if (number != null)
            super.setText( text );
    }

    public class ABMFilter extends DocumentFilter
    {
        public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
            throws BadLocationException
        {
            replace(fb, offs, 0, str, a);
        }

        public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a)
            throws BadLocationException
        {
            if ("0123456789".contains(str))
            {
                Document doc = fb.getDocument();
                StringBuilder sb = new StringBuilder( doc.getText(0, doc.getLength()) );

                int decimalOffset = sb.indexOf( decimal );

                if (decimalOffset != -1)
                {
                    sb.deleteCharAt(decimalOffset);
                    sb.insert(decimalOffset + 1, decimal);
                }

                sb.append(str);

                try
                {
                    String text = format.format( format.parse( sb.toString() ) );
                    super.replace(fb, 0, doc.getLength(), text, a);
                }
                catch(ParseException e) {}
            }
            else
                Toolkit.getDefaultToolkit().beep();
        }

        public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
            throws BadLocationException
        {
            Document doc = fb.getDocument();
            StringBuilder sb = new StringBuilder( doc.getText(0, doc.getLength()) );

            int decimalOffset = sb.indexOf( decimal );

            if (decimalOffset != -1)
            {
                sb.deleteCharAt(decimalOffset);
                sb.insert(decimalOffset - 1, decimal);
            }

            sb.deleteCharAt( sb.length() - 1) ;

            try
            {
                String text = format.format( format.parse( sb.toString() ) );
                super.replace(fb, 0, doc.getLength(), text, null);
            }
            catch(ParseException e) {}
        }
    }

    private static void createAndShowUI()
    {
//      DecimalFormat format = new DecimalFormat("###,##0.00");
        DecimalFormat format = new DecimalFormat("0000000000");
        ABMTextField abm = new ABMTextField( format );

        JPanel panel = new JPanel();
        panel.add( abm );

        JFrame frame = new JFrame("ABMTextField");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( panel );
        frame.setSize(200, 200);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

You can change the default mask as follows:

//DecimalFormat format = new DecimalFormat("###,##0.00");
DecimalFormat format = new DecimalFormat("0000000000");

Question:

I want to create a text field with this default text: R$0,00. Then, when user types the numbers, it automatically formats the field, like:

R$0,00

User presses 1: R$0,01

User presses 5: R$0,15

User presses 7: R$1,57

User presses 0: R$15,70

And, if the user delete something, only numbers will disappear. Any sugestion?

Thanks !


Answer:

you just have to write if statements and just setText of that text field and in the delete case just setText="" ..

Hope it helps

Question:

I would really appreciate your help; I'm using java (netbeans ide), i'm working with filechooser, when i choose a directory, i need to display it's path on a jtextfield. However nothing appears until the program is over (untill all the files of the directory are parsed and treated), I would like it to appear as soon as the program starts. Please help me out, here is my code:

    JFileChooser fch = new JFileChooser("C:\\");
    fch.addChoosableFileFilter(filter);

    fch.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int ret = fch.showOpenDialog(null); 
    int apr=0;
    if (ret==JFileChooser.APPROVE_OPTION)
    {
        apr=1;
        jTextField1.setText(fch.getSelectedFile().toString());
    }
    else jTextField1.setText("Nothing clicked!!!");
.......... the rest of the code .........

when I don't click the msg appears, yet when i do, the path won't apprear till after the program is finished


Answer:

The code of JFileChooser... probably resides in an ActionListener. This is handled on the sole event handling thread. So do an invokeLater.

@Override
public void actionPerformed(ActionEvent event) {
    ...

    EventQueue.invokeLater(new Runnable() { // Added
        ... rest of the code
    }); // Added
}

Here I think "rest of the code" might be causing the delay, but you might try differently.