Hot questions for Using JTextField in string

Question:

About the constructor of JTextField, the javadoc says:

public JTextField()

Constructs a new TextField. A default model is created, the initial string is null, and the number of columns is set to 0.

But when I use this constructor, the method getText() of JTextField returns an empty String, for example:

boolean b = new JTextField().getText().isEmpty();  // returns true.

Why the value returned by getText() is an empty String instead of null?


Answer:

JTextField get the text from the Document , default implementation PlainDocument never returns null. even though you tried to call JTextField.setText(null), it will just clear the value of the Document content, but still getText will return empty string.

Question:

I want to take only letters as a input in my name field.

I have already tried using the matches method but unfortunately something is wrong and the exception is being thrown.

Is there any other method of checking the same?

   import java.awt.BorderLayout;
   import java.awt.FlowLayout;
   import java.awt.GridBagConstraints;
   import java.awt.GridBagLayout;
   import java.awt.GridLayout;
   import java.awt.Insets;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
   import javax.swing.*;


    public class CreateAccount extends JFrame implements ActionListener{

    JPanel details = new JPanel(new GridBagLayout());

    JLabel fName= new JLabel("First Name:");
    JTextField firstNameField = new JTextField(10);

    JLabel lName= new JLabel("Last Name:");
    JTextField lastNameField = new JTextField(10);

    JLabel initialDeposit = new JLabel("Initial Deposit: ");
    JTextField initialDepositField = new JTextField(10);

    String accountTypes[] = {"Savings","Current"};

    JComboBox accountTypesComboBox = new JComboBox(accountTypes);
    JLabel accountType= new JLabel("Account type: ");

    JButton submit = new JButton("SUBMIT");
    JButton review = new JButton("REVIEW");

    Administrator admin = new Administrator();
    User u[] = new User[admin.maxNumberOfUsers];

    CreateAccount() {
        buildGui();
        setSize(400,300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void initialiseUserCount() {
        admin.numberOfSavingsAccount = 0;
        admin.numberOfCurrentAccount = 0;
        admin.numberOfUsers=0;
    }
    public void buildGui() {

        setTitle("New Account Form");

        //JPanel submitPanel = new JPanel();
        //submitPanel.add(submit);


        GridBagConstraints c = new GridBagConstraints();
        c.insets=new Insets(10,10,10,10);
        // Stretch components horizontally (but not vertically) 
        c.fill = GridBagConstraints.HORIZONTAL;
        // Components that are too short or narrow for their space
        // Should be pinned to the northwest (upper left) corner
        c.anchor = GridBagConstraints.NORTHWEST;
        // Give the "last" component as much space as possible
        c.weightx = 1.0;

        c.gridx=0;
        c.gridy=0;
        details.add(fName,c);
        c.gridx=1;
        c.gridy=0;
        details.add(firstNameField,c);
        c.gridx=0;
        c.gridy=1;
        details.add(lName,c);
        c.gridx=1;
        c.gridy=1;
        details.add(lastNameField,c);
        c.gridx=0;
        c.gridy=2;
        details.add(initialDeposit,c);
        c.gridx=1;
        c.gridy=2;
        details.add(initialDepositField,c);
        c.gridx=0;
        c.gridy=3;
        details.add(accountType,c);
        c.gridx=1;
        c.gridy=3;
        details.add(accountTypesComboBox,c);
        c.gridx=0;
        c.gridy=4;
        details.add(submit,c);
        c.gridx=1;
        c.gridy=4;
        details.add(review,c);
        add(details);

        firstNameField.addActionListener(this);
        review.addActionListener(this);

    }
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==firstNameField) {
            try {
                String uFName = firstNameField.getText().toString();

                if(!uFName.matches("[A-Za-z]+"))
                    throw new Exception();
            }
            catch(Exception e1) {
                firstNameField.setText("");
                JOptionPane.showMessageDialog(firstNameField,"Please enter a valid name!");
            }
        }
    }
}

Answer:

Use a DocumentFilter. It will allow you to perform real time validation of the text fields

See Implementing a Document Filter and DocumentFilter Examples for more details

For example...

public class CharFilter extends DocumentFilter {

    public void insertString(DocumentFilter.FilterBypass fb, int offset,
                    String string, AttributeSet attr)
                    throws BadLocationException {

        StringBuffer buffer = new StringBuffer(string);
        for (int i = buffer.length() - 1; i >= 0; i--) {
            char ch = buffer.charAt(i);
            if (!Character.isLetter(ch)) {
                buffer.deleteCharAt(i);
            }
        }
        super.insertString(fb, offset, buffer.toString(), attr);
    }

    public void replace(DocumentFilter.FilterBypass fb,
                    int offset, int length, String string, AttributeSet attr) throws BadLocationException {
        if (length > 0) {
            fb.remove(offset, length);
        }
        insertString(fb, offset, string, attr);
    }
}

And applied using something like...

JTextField firstNameField = new JTextField(20);
((AbstractDocument)firstNameField.getDocument()).setDocumentFilter(new CharFilter());

Question:

I keep getting an error for empty string as you can see below

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""

I am unsure why I keep getting this error since I do not try to calculate without typing a number within the JTextField. Below is the code I am using for the calculate button which is fairly simple.

private void ButtonCalculateActionPerformed(java.awt.event.ActionEvent evt) {                                                
         Height = Integer.parseInt(this.TextFieldHeight.getText());
         Weight = Integer.parseInt(this.TextFieldWeight.getText());
         BMI = Integer.parseInt(this.TextFieldBMI.getText());
         answer = Height + Weight;
        this.TextFieldBMI.setText("The answer is: " + answer);
    }                                               

These are the defined variables

//variables
    static int Height;
    static int Weight;
    static int BMI;
    static int answer;

Answer:

This happens when the TextField is empty (getText() returns ""), so the Integer class can't parse anything and throws an exception instead. You should sourround the parsing code with try/catch:

try{
    Height = Integer.parseInt(this.TextFieldHeight.getText());
    Weight = Integer.parseInt(this.TextFieldWeight.getText());
    BMI = Integer.parseInt(this.TextFieldBMI.getText());
    answer = Height + Weight;
    this.TextFieldBMI.setText("The answer is: " + answer);
catch(NumberFormatEeceptinon e){
    //So something when paring failed, e.g. show a error message
}

Question:

I'm creating a simple program that gets 2 certain strings on an input from a JTextArea. It needs to find a non-integer string then finds an integer. All values matching from the same non-integer string will add and display the result in a JTextField. Like in the example below, all numbers who matches "ax" will be added together and the final result will be displayed in the texfield below the label "AX Box" (25 + 5 = 30)

My following code:

    JTextField ax, bx, cx, dx;
    int totalAX, totalBX, totalCX, totalDX;
    String[] lines = textArea.getText().split("\\n"); // split lines
    System.out.println(Arrays.toString(lines)); // convert each line to string
    for (int i = 0; i < lines.length; i++) {
        if (lines.contains("ax") {
            // add each numbers.
            // for example, 25 + 5
            totalAX = totalAX + i;
            ax.setText("Total: " +totalAX);
        }
}

My problem is that the program cannot find the substring "ax", "bx" and so on. What's the best approach in this? I get errors like:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "ax"


Answer:

I'm not sure that you're actually splitting the array, the escape sequence for a line jump is \n, you have it as \\n.

You are also only printing the array lines if you need to convert it to String you should be reassigning a value for it like:

for (int i = 0; i < lines.length; i++) {
     String line = lines[i].toString();

And I'm pretty sure you don't need the toString() as it should come as a String variable from the textBox

After this you need to find if it contains the "ax" and the index where it is first contained, keep that number and use it to substring the whole line to find the number, so bearing in mind that the number should be in the last place of the string you would be looking at something like this after (inside) the loop:

    if (line.contains("ax") {
      int theIndex = line.indexOf("ax");
      line = line.substring(theIndex);
}

Or in a oneliner:

 if (line.contains("ax") {
  line = line.substring(line.indexOf("ax"));
}

Question:

I have a JTextField that displays a line number like this : 2 or 2.1 or 2.1.1 etc. I would like the size of the JTextField to always stay the same but I want the font size to decrease/increase so that the text is always fully displayed and it fills the text field.

I'm wondering if there's a simple way to do this (I don't mind using a different swing component) or will I have to do it manually i.e. by checking the size of the text and changing the text field size?

I'd obviously prefer not to do it this way since the size increment may not be a nice number to go from e.g. 2.1 to 2.1.1.


Answer:

the JTextField becomes smaller as the font decreases.

The preferred size of the text field is based on the font. So the size will increase/decrease as the font size changes. Override the getPreferredSize() method of JTextField to provide your own implementation.

Maybe something like:

Font current = getFont();
setFont( UIManager.getFont("TextField.font") );
Dimension preferred = super.getPreferredSize();
setFont( current );
return preferred;

Question:

I'm trying to update received ByteBuffer data (converted to String) to JTextField, but text field is printing output data along with junk values, even after trimming the string.

But in output console it is printing proper data, when it comes to text field in GUI it's printing junk data along with proper data.

import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;

public class UsbRead
{
    static final byte IN_ENDPOINT1 = (byte) 0x82;
    static final int TIMEOUT = 100;
    static final byte INTERFACE = 1;
    static final byte interfaceNum = 1;
    static String s=new String();
    static String dd=new String();

    public static String read(DeviceHandle handle) 
    {
        try{
            System.out.println("-----read-----");
            ByteBuffer buffer = BufferUtils.allocateByteBuffer(30);
            IntBuffer transferred = BufferUtils.allocateIntBuffer();
            System.out.println("capacity-->"+buffer.capacity());
            int result=LibUsb.bulkTransfer(handle, IN_ENDPOINT1, buffer, 
           transferred, TIMEOUT);
            if (result != LibUsb.SUCCESS)
            {
                throw new LibUsbException("Unable to read data", result);
            }
            else
            {
                System.out.println("---------------------------read----------");
                System.out.println(transferred.get() + "-------- bytes read from device");
                s="";
                s = StandardCharsets.UTF_8.decode(buffer).toString();
                System.out.println("s--"+s);
                s.trim();
                WisePanel4.textField_1.setText(s);
                dd=s;
                System.out.println("received data ->"+dd);
            }
            return dd;
        }
        catch(Exception e)
        {
            System.out.println("-*----read time out");

        }
        return dd;
    }
}

output -->

---------------------------read----------

20-------- bytes read from device

s--192.168.1.108

received data ->192.168.1.108

Please check the image of GUI. It is printing junk value with proper data:


Answer:

Most probably you are receiving a C-String as a response. So the String is terminated by a NUL ('\0') character. Try getting the value using:

s = s.substring(0, s.indexOf('\0'));

Question:

I was hoping to retrieve the newline character at the end of the text in a JTextField, however after setting the text field's text to my string, it has been modified to be a space character. The code below highlights the problem.

Is it possible to preserve the \n in the text field?

import javax.swing.JTextField;

public class StackOver {
    public static void main(String[] args) {
        String hasNewLineEscapeCharacter = makeStringWithNewLineCharacter();
        JTextField backgroundText = new JTextField(90);
        backgroundText.setText(hasNewLineEscapeCharacter);
        char spaceChar = backgroundText.getText().charAt(backgroundText.getText().length()-1);
        char newLineChar = hasNewLineEscapeCharacter.charAt(needsNewLineEscapeCharacter.length()-1);
    }

    public static String makeStringWithNewLineCharacter() {
        String str = "hello,world!";
        str += ('\n');
        return str;
    }       
}

Answer:

Is it possible to preserve the '\n' in my JTextField?

A JTextField uses a PlainDocument which contains a property that filters the "\n" and replaces it with a space character.

To preserve the newline character in the text field you can try:

textField.getDocument().putProperty("filterNewlines", Boolean.FALSE);

However, this will cause the text to display on two lines just like a text area.

So as suggested above you should just be using a JTextArea.

There is no way to display text that contains a newline character on a single line.

What you might want to do is store some other unprintable character in the text string and then use a String.replaceAll(...) if you ever need to access the text with the newline character added back in.

Question:

I'm building a tool to generate a script of commands for integration purposes for some equipment using Java Swing. So basically the tool takes the user inputs in some text fields and then build the needed commands with the user variable.

At the end of my script I'm displaying the commands in a text area (textOut) by doing this:

command = "add user " + textUser.getText() + " Gender " + textGender.getText();
                textOut.setText(command);

This gives me a command like this:

add user Tom Gender Male

I've succeeded to have the tool running and giving the needed output commands in different lines, but now for example if the Gender field is optional and user left it empty, I want to also remove it from the output command because now if the field is empty it give this output:

add user Tom Gender

I want it to look like this

add user Tom

Any idea how can I do a check if a text field is empty (I found some ways to check if the value is null)? I also need to change the output command according to this.


Answer:

I'm assuming you want the Java solution (though your title says Javascript):

    final StringBuilder command = new StringBuilder();

    command
        .append("add user ")
        .append(textUser.getText());

    final String gender = textGender.getText();

    if(gender != null && !gender.equals("")) {
        command
            .append(" Gender ")
            .append(gender);
    }

    textOut.setText(command.toString());

Question:

I have looked at similar questions on this site but I cannot seem to grasp the concept, so I have to post my own question to get an answer specific to me.

I am trying to get the text entered into the JTextField txtAddEng added to the JComboBox engBox by clicking the JButton btnAdd.

    engBox = new JComboBox();
    engBox.setMaximumRowCount(1000);
    engBox.setModel(new DefaultComboBoxModel(new String[] {"Select an Engagement"}));
    engBox.setBounds(10, 0, 181, 20);       
    sopPanel.add(engBox);

    txtAddEng = new JTextField();
    txtAddEng.setHorizontalAlignment(SwingConstants.CENTER);
    txtAddEng.setToolTipText("Type ENG-#### and click Add");
    txtAddEng.setText("Add an engagement?");
    txtAddEng.setBounds(201, 0, 181, 20);
    sopPanel.add(txtAddEng);
    txtAddEng.setColumns(10);

    JButton btnAdd = new JButton("Add");
    btnAdd.setBounds(383, 3, 51, 17);
    btnAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent clickAdd) {
            txtAddEng.toString();
            engBox.add(txtAddEng);
        }
    });

Answer:

txtAddEng.toString();

That statement does nothing. It just invokes the toString() method but never assigns it to a variable. Get rid of that statement.

engBox.add(txtAddEng);

You don't want to add the text field to the combo box. You want to add the text in the text field the to model of the combo box.

So the code should be;

engBox.addItem( txtAddEng.getText() );

Read the section from the Swing tutorial on How to Use Combo Boxes for more information and working examples. Keep a link to the tutorial handy for all Swing basics.

Question:


Answer:

You need to use the .equals() string method so change

if(userAttempt == correctPW) {

to

if(userAttempt.equals(correctPW)) {

== checks if it is the same object (in memory) .equals() checks if they have the same value (see What is the difference between == vs equals() in Java? for more in depth detail on this difference)

Question:

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:

        //9


        txtTot.setText(jComboBox1.getSelectedItem().toString());
        tot= Double.parseDouble(txtTot.getText());
        CMB= (Double)jComboBox1.getSelectedItem();
        Total2=tot+CMB;
        txtTot.setText(Double.toString(Total2));

    }   

From the ComboBox I'm setting the jtextfield and the second line I'm taking the string from the textfield and trying to convert it into a double.

Error below:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
    at test.Test.jComboBox1ActionPerformed(Test.java:392)
    at test.Test.access$600(Test.java:18)
    at test.Test$7.actionPerformed(Test.java:134)
    at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1258)
    at javax.swing.JComboBox.setSelectedItem(JComboBox.java:586)
    at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)

Answer:

To me it seems like you are selecting a value from a combobox then trying to add them together to create a grand total, with the total being updated every time you select a new value from the combobox.

This seems to be working for me, Note I've taken the first line away because it interfered with the existing total.

tot= Double.parseDouble(txtTot.getText());
CMB = Double.parseDouble((String) jComboBox1.getSelectedItem());
Total2=tot+CMB;
txtTot.setText(Double.toString(Total2));

Question:

I've got question regarding to typing in JTextField. My program search thru few csv files and look for specified in JTextField string. I have add to readLine function ".toLowerCase" to read all strings as lowercase. Is it possible to set JTextField to automatically convert uppercase to lower case while writing to JTextField?

if (line.toLowerCase().contains(searchedString))...


Answer:

Yes, you can use the KeyListener and when a key is pressed in the textfield, you will make the input string lowerCase while keeping the cursor position where it was. Like the code below:

jTextField1.addKeyListener(new KeyListener() {
    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int pos = jTextField1.getCaretPosition();
        jTextField1.setText(jTextField1.getText().toLowerCase());
        jTextField1.setCaretPosition(pos);
    }
});

Source:

  • Value Change Listener to JTextField
  • Finding the cursor text position in JTextField

Question:

I'm new to Java programming and I'm now developing a simple application. Now I'm focused on finding a solution on this problem: checking if a String contained in a JTextField contains spaces between each of its characters, like: "1 + 2 - 3 + 7" (which has spaces between every char), but I can't find a solution atm. Could you help me? Thanks in advance ;)


Answer:

Apart from making a Method i would suggest using a Pattern: ^(\d + )*\d$

This Regex allows easy modifications, to further restrict or allow certain combinations - Easily allowing numbers instead of digits. You might want to use a compiled and final Pattern in an utility class:

public static final Pattern P = Pattern.compile("^(\\d \\+ )*\\d$");

Testcase:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

// [...] 

public static final Pattern P = Pattern.compile("^(\\d [\\+\\-] )*\\d$");

public static void main(String[] args) {
    final String[] testCases = {
        "1+2", "2 + 3", "5 + 6 - 4", "1 + ", "6 6"
    };

    for(String s:testCases) {
        final Matcher m = P.matcher(s);
        if(m.matches()) {
            System.out.println("String valid: " + s);
        } else {
            System.out.println("String invalid: " + s);
        }
    }
}

Given output:

String invalid: 1+2

String valid: 2 + 3

String valid: 5 + 6 - 4

String invalid: 1 +

String invalid: 6 6

Question:

I'm using Java Ready 1.4. I have already referred to the codes posted for getting the value from JTextField and tried them, but I get this compliation error: No method named "getText" was found in type "java.lang.String."

My program:

import java.awt.*; //for Dimension
import javax.swing.*; //for GUI components
import java.awt.event.*; //for MessageListener

public class MortgageCalculator extends JFrame implements ActionListener
{
public String nameField, ageField, incomeField, priceField, downPayField, interestRateField, paymentField, amortField;

public MortgageCalculator ()
{
    //Frame
    JFrame frame = new JFrame ();
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame.setSize (new Dimension (300, 250));
    frame.setTitle ("Mortgage Calculator");
    frame.getContentPane ().setLayout (new BorderLayout ());

    //User Information (Input) - Center Panel
    JPanel centerPanel = new JPanel (new GridLayout (16, 1));
    //Personal Information
    centerPanel.add (new JLabel ("Personal Information", SwingConstants.CENTER));
    centerPanel.add (new JLabel ("Full Name:"));
    final JTextField nameField = new JTextField ();
    centerPanel.add (nameField);
    centerPanel.add (new JLabel ("Your Age:"));
    final JTextField ageField = new JTextField ();
    centerPanel.add (ageField);
    centerPanel.add (new JLabel ("Yearly Income:"));
    final JTextField incomeField = new JTextField ();
    centerPanel.add (incomeField);
    centerPanel.add (new JLabel ());
    //Mortgage Information
    centerPanel.add (new JLabel ("Mortgage Information", SwingConstants.CENTER));
    centerPanel.add (new JLabel ("Price of Property:"));
    final JTextField priceField = new JTextField ();
    centerPanel.add (priceField);
    centerPanel.add (new JLabel ("Down Payment:"));
    final JTextField downPayField = new JTextField ();
    centerPanel.add (downPayField);
    centerPanel.add (new JLabel ("Interest Rate (%):"));
    final JTextField interestRateField = new JTextField ();
    centerPanel.add (interestRateField);
    centerPanel.add (new JLabel ("Amortization Period (Years):"));
    frame.getContentPane ().add (centerPanel, BorderLayout.CENTER);

    //User Options (Input) - South Panel
    JPanel southPanel = new JPanel (new GridLayout (8, 3));
    //Payment Option
    southPanel.add (new JLabel ("Payment:"));
    southPanel.add (new JLabel ("Type in 1, 2 or 3"));
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ("1. Weekly"));
    southPanel.add (new JLabel ("2. Biweekly"));
    southPanel.add (new JLabel ("3. Monthly"));
    final JTextField paymentField = new JTextField ();
    southPanel.add (paymentField);
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ());

    //Amortization Period Option
    southPanel.add (new JLabel ("Amortization Period:"));
    southPanel.add (new JLabel ("Type in 1, 2 or 3"));
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ("1. 20 years"));
    southPanel.add (new JLabel ("2. 25 years"));
    southPanel.add (new JLabel ("3. 30 years"));
    final JTextField amortField = new JTextField ();
    southPanel.add (amortField);
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ());
    //To add a blank line in frame, added three blank JLabels because it is 3 horiontal for grid layout
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ());
    southPanel.add (new JLabel ());
    southPanel.add (new JButton ("Clear Information"));
    southPanel.add (new JLabel ());
    JButton nextButton = new JButton ("Next");
    southPanel.add (nextButton);

    frame.getContentPane ().add (southPanel, BorderLayout.SOUTH);


    frame.pack ();
    frame.setVisible (true);


    nextButton.addActionListener (this);

}


public static void main (String[] args)
{
    MortgageCalculator mainApp = new MortgageCalculator ();
}


public void actionPerformed (ActionEvent e)
{
    //Gets the personal information from the text fields
    String name;
    int age, payment, amort;
    double income, price, downPay, interestRate;

    name = nameField.getText ();
    age = Integer.parseInt (ageField.getText ());
    income = Double.parseDouble (incomeField.getText ());
    price = Double.parseDouble (priceField.getText ());
    downPay = Double.parseDouble (downPayField.getText ());
    interestRate = Double.parseDouble (interestRateField.getText ());
    payment = Integer.parseInt (paymentField.getText ());
    amort = Integer.parseInt (amortField.getText ());

    interestRate = interestRate / 100;


    //Output frame
    JFrame frame2 = new JFrame ();
    frame2.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame2.setSize (new Dimension (300, 250));
    frame2.setTitle ("Mortgage Calculator");
    frame2.getContentPane ().setLayout (new BorderLayout ());

    JPanel westPanel2 = new JPanel (new GridLayout (3, 1));
    JLabel nameLabel = new JLabel ("Name: " + name);
    westPanel2.add (nameLabel);
    JLabel ageLabel = new JLabel ("Age: " + age);
    westPanel2.add (ageLabel);
    JLabel incomeLabel = new JLabel ("Yearly Income: $" + income);
    westPanel2.add (incomeLabel);
    frame2.getContentPane ().add (westPanel2, BorderLayout.WEST);

    JPanel centerPanel2 = new JPanel (new GridLayout (3, 1));
    JLabel priceLabel = new JLabel ("    Price of property: $" + price);
    centerPanel2.add (priceLabel);
    JLabel downPayLabel = new JLabel ("    Down Payment: $" + downPay);
    centerPanel2.add (downPayLabel);
    JLabel interestRateLabel = new JLabel ("    Interest Rate: " + income);
    centerPanel2.add (interestRateLabel);
    frame2.getContentPane ().add (centerPanel2, BorderLayout.CENTER);


    double interest, numerator, l, denominator, payPerPeriod, initialP, mortgageYearly;
    if (payment == 1)
    {
        interest = 1 + interestRate / 52;
        if (amort == 1)
        {
            l = Math.pow (interest, 20 * 52);
            numerator = l * interest;
            denominator = l - 1;
            initialP = price - downPay;
            payPerPeriod = (numerator / denominator) * initialP;
        }
        else if (amort == 2)
        {
            l = Math.pow (interest, 25 * 52);
            numerator = l * interest;
            denominator = l - 1;
            initialP = price - downPay;
            payPerPeriod = (numerator / denominator) * initialP;
        }
        else // 3. amort30
        {
            l = Math.pow (interest, 30 * 52);
            numerator = l * interest;
            denominator = l - 1;
            initialP = price - downPay;
            payPerPeriod = (numerator / denominator) * initialP;
        }
        mortgageYearly = payPerPeriod * 52;
    }
    else if (payment == 2)
    {
        interest = 1 + interestRate / 26;
        if (amort == 1)
        {
            l = Math.pow (interest, 20 * 26);
            numerator = l * interest;
            denominator = l - 1;
            initialP = price - downPay;
            payPerPeriod = (numerator / denominator) * initialP;
        }
        else if (amort == 2)
        {
            l = Math.pow (interest, 25 * 26);
            numerator = l * interest;
            denominator = l - 1;
            initialP = price - downPay;
            payPerPeriod = (numerator / denominator) * initialP;
        }
        else // 3. amort30
        {
            l = Math.pow (interest, 30 * 26);
            numerator = l * interest;
            denominator = l - 1;
            initialP = price - downPay;
            payPerPeriod = (numerator / denominator) * initialP;
        }
        mortgageYearly = payPerPeriod * 26;


    }
    else //3. monthly payment
    {
        interest = 1 + interestRate / 12;
        if (amort == 1)
        {
            l = Math.pow (interest, 20 * 12);
            numerator = l * interest;
            denominator = l - 1;
            initialP = price - downPay;
            payPerPeriod = (numerator / denominator) * initialP;
        }
        else if (amort == 2)
        {
            l = Math.pow (interest, 25 * 12);
            numerator = l * interest;
            denominator = l - 1;
            initialP = price - downPay;
            payPerPeriod = (numerator / denominator) * initialP;
        }
        else // 2. amort30
        {
            l = Math.pow (interest, 30 * 12);
            numerator = l * interest;
            denominator = l - 1;
            initialP = price - downPay;
            payPerPeriod = (numerator / denominator) * initialP;

        }
        mortgageYearly = payPerPeriod * 12;
    }


    JPanel eastPanel2 = new JPanel (new GridLayout (3, 1));
    JLabel payTotalLabel = new JLabel ("    Payment Total: $" + initialP);
    eastPanel2.add (priceLabel);
    JLabel payPerPeriodLabel = new JLabel ("    Payment per period: $" + payPerPeriod);
    eastPanel2.add (payPerPeriodLabel);

    frame2.getContentPane ().add (eastPanel2, BorderLayout.EAST);


    JPanel southPanel2 = new JPanel (new GridLayout (2, 1));
    double minimumIncome = mortgageYearly / 0.28;
    JLabel minimumLabel = new JLabel ("    Minimum Yearly Income: $" + minimumIncome);
    eastPanel2.add (priceLabel);

    if (minimumIncome > income)
    {
        JLabel qualifiedLabel = new JLabel ("You are not qualified for the mortgage");
        eastPanel2.add (qualifiedLabel);
    }
    else
    {
        JLabel qualifiedLabel = new JLabel ("You are qualified for the mortgage");
        eastPanel2.add (qualifiedLabel);
    }


    frame2.getContentPane ().add (eastPanel2, BorderLayout.EAST);



    frame2.pack ();
    frame2.setVisible (true);



}

}


Answer:

This error is a simple one, but I can see why it could trip you up. Basically, all of your field variables, like nameField and ageField are defined as a String at the top of your class. Change the String in this line:

public String nameField, ageField, incomeField, priceField, downPayField, interestRateField, paymentField, amortField;

To JTextField. Then, inside of your main method, instead of defining each field like this: final JTextField incomeField = new JTextField ();

Do this instead: incomeField = new JTextField ();

Question:

I have unusual issue something is working a bit to well. I have written a DocumentFilter witch allow user input only as numbers, DocumentFilter add dash on it's own in proper place during writing. This way inJTextField is visible date like this is: "2016-05-01". The problem is that JTextField is not always filled in by user, sometimes it must be set by program. But when I use code setText("2016-05-01"), it don't display properly, all dash are gone. How to make it work ? I tried to change DocumentFilter to allow dash, but this why cause problems in many other places. I probably will end up writting another DocumentFilter just for this but maybe there is a other way? Is it possible to append JTextField char by char ? Is there a way to switch on an off the DocumentFilter, or mayby it's posible to change smartly DocumentFilter so it will not crush in oder palces and work here as well? Below part of code for DocumentFilter

  public void replace(FilterBypass fb, int offs, int length, String str,
    AttributeSet a) throws BadLocationException {

if (str == null || str.equals(""))
{
    super.replace(fb, offs, length, str, a); 
}
else
{
    StringBuffer buffer = new StringBuffer(str);
    for (int i = buffer.length() - 1; i >= 0; i--)
    {
    char ch = buffer.charAt(i);
    if (!Character.isDigit(ch))
    {
        buffer.deleteCharAt(i);
    }
    }

    str = buffer.toString();
    //sign and sign2 is char number were separator(sep) is written 
    if (fb.getDocument().getLength() + str.length() == sign)
    {
    str = str + sep;
    }
    if (fb.getDocument().getLength() + str.length() == sign2)
    {
    str = str + sep;
    }


    if ((fb.getDocument().getLength() + str.length() - length) <= maxCharacters)
    super.replace(fb, offs, length, str, a);
    else
    Toolkit.getDefaultToolkit().beep();
}

Answer:

You can do something like this:

@Override
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
    if (str == null || str.equals("")) {
        super.replace(fb, offs, length, str, a);
    } else {
        // check if 'str' contains 8 digits
        if (str.matches("^\\d{8}$")) {
            // add the dashes
            super.replace(fb, offs, length, str.replaceAll("(\\d{4})(\\d{2})(\\d{2})", "$1-$2-$3"), a);
        } else {
            StringBuffer buffer = new StringBuffer(str);
            for (int i = buffer.length() - 1; i >= 0; i--) {
                char ch = buffer.charAt(i);
                if (!Character.isDigit(ch)) {
                    buffer.deleteCharAt(i);
                }
            }

            str = buffer.toString();
            // sign and sign2 is char number were separator(sep) is written
            if (fb.getDocument().getLength() + str.length() == sign) {
                str = str + sep;
            }
            if (fb.getDocument().getLength() + str.length() == sign2) {
                str = str + sep;
            }

            if ((fb.getDocument().getLength() + str.length() - length) <= maxCharacters)
                super.replace(fb, offs, length, str, a);
            else
                Toolkit.getDefaultToolkit().beep();
        }
    }
}

and set the text using this:

textField.setText("20160420");

Question:

My program works with birthday's and age's. I have trouble with trying to convert my JTextField strings to doubles. I used the parse method but still received a error. Please Help!

public class MyPaymentFrame extends JFrame implements ActionListener {

    JTextField txtAge;
    JTextField txtDate;

        public MyPaymentFrame()  {
        Container mycnt = getContentPane();
        mycnt.setLayout(new FlowLayout());

        Color c = new Color(56, 100, 20);
        Font F = new Font("Arial", Font.ITALIC, 20);

        mycnt.add(new JLabel("Enter your Age"));
        txtAge = new JTextField(15);
        mycnt.add(txtAmount);


        mycnt.add(new JLabel("Enter birthdate"));
        txtDate = new JTextField(10);
        mycnt.add(txtDate);

    }
        if (e.getActionCommand().equals("Clear")) {
            txtAge.setText("");
            txtDate.setText("");
        }

        if (e.getActionCommand().equals("Calculate")) {
            // Converting String to Double
            double Amount = Double.parseDouble(txtMonth);

        }

    }
    public static void main(String[] args) {

        Theframe myframe = new Theframe();

    }

}

Answer:

Apparently txtMonth is a JTexfield, but the Double.parseDouble method receives a String. Check the method's javadoc here.

Try using:

double Amount = Double.parseDouble(txtMonth.getText());

Also, this method will throw a NumberFormatException if the text can't be converted to double.

Question:

package javaisnotbannana;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
public class  Javaisnotbannana{

    public static void main(String[] args) { 
        window();
    }       
////////////////////////////////////////////////////
public static void window()
    {
     JFrame window= new JFrame();
     JPanel jp = new JPanel();
     JLabel jl = new JLabel();
     JTextField jt = new JTextField(30);
     JButton jb = new JButton("Enter");
     window.setTitle("ThisisTitleofWindow");
     window.setVisible(true);
     window.setSize(500, 500);
     window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     //textfield
     jp.add(jt);
     jt.addActionListener(new ActionListener()
     {
     public void actionPerformed(ActionEvent e)
     {
     String inoutt = jt.getText();

     jl.setText(inoutt); 
     }
     });

Why dose this lower section have the problem "Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range:(how ever many characters i entered)".str is receiving what is typed in the Jtextfield and im trying to filter the input to give a different output. With out a filter it works fine like above just press enter,but when i try to press the button i and filter i get an error.

//button
     jp.add(jb);
     jb.addActionListener(new ActionListener()
     {
     public void actionPerformed(ActionEvent e)
     {
     String str = jt.getText();
     String text="";
     int A=0;
     int B=1;
     int C=2;
     for(int num=0;num<=str.length()/3;num++)
        {
            if (str.charAt(A) == 'T'&&str.charAt(B) == 'A'&&str.charAt(C)=='S')
            {
            text+="smell tasty";
            }
            else if(str.charAt(A) == 'B'&&str.charAt(B) == 'A'&&str.charAt(C)=='N')
            {
            text+="bannanas";
            }
            A+=3;
            B+=3;
            C+=3;
        }
     jl.setText(text);
     }
     });
     jp.add(jl);
     window.add(jp);
    }
}

Answer:

your index is overshooting use this instead

for(int num=0;num<str.length()/3;num++)

just < not <=

Question:

I'm making a text processing program, and I want if the user press 'a' ('a' is just for demonstration, I have a list of special characters like that), it will replace some characters from the caret to the left with a string.

I have tried "setText" method but it replaced then moved the caret and the text component scrolled to the end, what I want is the caret not to move anywhere else and the text component not to scroll to the end, how can I code to do that(I am overriding the processKeyEvent)?

Any help would be appreciated.


Answer:

Try to use document filter:

    JTextArea textArea = new JTextArea();

    ((AbstractDocument) textArea.getDocument()).setDocumentFilter(new DocumentFilter() {            
        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                throws BadLocationException {

            if ("a".equals(text)) {
                text = "B";
            }               

            super.replace(fb, offset, length, text, attrs);
        }
    });