(i'm sry if i make english mistake my native language is french) for a university project i've to make a little software, the user need to inmput a number, it's why i used a JFormattedTextField, but i also need to allow an empty field and i don't know how to do it, if someone is kind enought to help me i would be more than happy.
the code that i use:
NumberFormat format = NumberFormat.getInstance();
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setAllowsInvalid(false);
formatter.setCommitsOnValidEdit(true);
textID = new JFormattedTextField(formatter);
I find this here JFormattedTextField problem
final JFormattedTextField field = new JFormattedTextField(NumberFormat.getInstance()) {
@Override
protected void processFocusEvent(final FocusEvent e) {
if (e.isTemporary()) {
return;
}
if (e.getID() == FocusEvent.FOCUS_LOST) {
if (getText() == null || getText().isEmpty()) {
setValue(null);
}
}
super.processFocusEvent(e);
}};
but i don't know to use it so i try to create my own version with my knowledge in class
class JFormattedTextFieldCorrected extends JFormattedTextField{
public JFormattedTextFieldCorrected(NumberFormatter formatter) {
super(formatter);
}
@Override
protected void processFocusEvent(final FocusEvent e) {
if (e.isTemporary()) {
return;
}
if (e.getID() == FocusEvent.FOCUS_LOST) {
if (getText() == null || getText().isEmpty()) {
setValue(null);
}
}
super.processFocusEvent(e);
}}
of course i changed JFormattedTextField by JFormattedTextFieldCorrected but i didn't manage to make it work. Have a nice day.
[edit this is a minimal reproductible exemple, to use it just enter a random number and try to erase it]
import java.text.NumberFormat;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.text.NumberFormatter;
public class MinimalExempleTextFormat extends JFrame{
private JFormattedTextField textID;
public MinimalExempleTextFormat() {
NumberFormat format = NumberFormat.getInstance();
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setAllowsInvalid(false);
formatter.setCommitsOnValidEdit(true);
getContentPane().setLayout(null);
textID = new JFormattedTextField(formatter);
textID.setBounds(208, 0, 226, 261);
getContentPane().add(textID);
this.setSize(500,500);
}
public static void main(String[] args) {
MinimalExempleTextFormat m=new MinimalExempleTextFormat();
m.setVisible(true);
}
}
[edit i find a way to avoid this problem]