codenoob
codenoob

Reputation: 1

How can I set the value of a JFormatedTextField to an invalid String before it gets changed by the user?

Because of a project, I want to know how to set the value of a JFormatedTextField, in a Java Swing GUI, to an invalid String, before the user changes the value by himself/herself.

Considering the fact that all the iddentifer names in the original code, which contains additional code, which is not useful for this question, I decided to write a new short code, which contains the important part, for my question.

This is a shortened version of my code:

import javax.swing.*;
import javax.swing.text.*;
import java.text.*;
import java.awt.*;
public class myGUI{
    private JFrame f;
    private JPanel p;
    private JFormattedTextField ftf;
    private NumberFormat nf;
    private NumberFormatter nfter;
    public myGUI(){
        f = new JFrame("My Window");
        f.setSize(960,450);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        p = new JPanel();
        f.add(p);
        p.setLayout(new FlowLayout());
        nf = NumberFormat.getInstance();
        nfter = new NumberFormatter(nf);
        nfter.setAllowsInvalid(false);
        ftf = new JFormattedTextField(nfter);
        p.add(ftf);
        ftf.setValue("I want this as my ftfs value before it gets changed");
    }
}

When I execute this code, I get this error message:

java.lang.IllegalArgumentException: Cannot format given Object as a Number (in java.text.DecimalFormat)

I tried to solve this problem by myself by changing "nfter.setAllowsInvalid(false);" to "nfter.setAllowsInvalid(true);", but I received the same result.

Since I am not really familiar to Swing and only familiar to the most basic things about Java, I hope you can help me, with your experance and knowledge.

Upvotes: 0

Views: 59

Answers (1)

bitdancer
bitdancer

Reputation: 1365

Please use setText instead of setValue. You should put a number inside setValue method like setValue(99).

ftf.setText("I want this as my ftfs value before it gets changed");

And don't forget nfr.setCommitsOnValidEdit(true) if you want your default text to be formatted as a number at beginning. Otherwise you will get null value before you typing something.

Upvotes: 0

Related Questions