Instead of using a document filter, or a FormatMask I am trying something different. Here is the requirements. Have a JTextField only accept/have one character of input allowed into it at a time, the only allowed input is numbers 1-9 think of the game Sudoku, all other input is invalid and should not be allowed. I tried handleing this with both of the above ideas and still kept getting error beeps for backspace and delete keys when using focus on the JTextField.
So I thought why not have something as a buffer that can ignore all input data I did not want to accept here is my solution.
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.event.*;
public class MaskField
{
JFrame thisframe;
JPanel jPanel1 = new JPanel();
JTextField jTextField1 = new JTextField();
public MaskField()
{
thisframe = new JFrame();
jTextField1.addFocusListener(new FocusListener(){
@Override
public void focusLost(FocusEvent e){}
@Override
public void focusGained(FocusEvent e)
{
JTextField thisfield = (JTextField)e.getSource();
thisfield.getParent().requestFocus();
}
});
jPanel1.addKeyListener(new KeyAdapter()
{
@Override
public void keyReleased(KeyEvent e){}
@Override
public void keyTyped(KeyEvent e){}
@Override
public void keyPressed(KeyEvent e)
{
JPanel thispanel = (JPanel)e.getSource();
Component[] complist = thispanel.getComponents();
JTextField thisfield = (JTextField)complist[0];
text = thisfield.getText();
if(Character.isDigit(e.getKeyChar()) && !"0".equals(Character.toString(e.getKeyChar())))
{
thisfield.setText(Character.toString(e.getKeyChar()));
}
if(e.getKeyCode() == 127 || e.getKeyCode() == 8)
thisfield.setText("");
}
});
jPanel1.setLayout(new GridLayout(1,1));
jTextField1.setText("");
jPanel1.add(jTextField1);
thisframe.add(jPanel1);
thisframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisframe.setVisible(true);
thisframe.pack();
}
public static void main(String args[])
{
new MaskField();
}
}
I would greatly appreciate any different ideas about how to handle this because getting and changing the JTextField data is so verbose.