I want to filter the key that are pressed on JTextField.
I want that only numbers are allowed, and if other character are pressed it remove it or don't allow the storage on the text field.
I'm thinking to use an addKeyListener, and use the methods: key pressed and key released.
Any Ideas?
Try this
final JTextField myTextField = new JTextField();
myTextField.addKeyListener(new KeyListener() {
String oldText = "";
public void keyPressed(KeyEvent keyEvent) {
// Store old text in a temporary variable
oldText = myTextField.getText();
}
public void keyReleased(KeyEvent keyEvent) {
// Make sure that the user is typing a number else replace with old text.
int charCode = (int)keyEvent.getKeyChar();
if (charCode < 48 || charCode > 57){
myTextField.setText(oldText); // Replace with old text.
}
}
public void keyTyped(KeyEvent keyEvent) {
}
});
No offence, Mr. Ravindra's answer is correct but it fails when you type continuously ..
I hope this helps :
final JTextField myTextFiled=new JTextField();
JFrame frame=new JFrame("onlyNums");
KeyListener myKeyListner=new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyChar()>='0' && e.getKeyChar()<='9')
myTextFiled.setText(myTextFiled.getText()+e.getKeyChar());
else if(e.getKeyChar()==KeyEvent.VK_BACK_SPACE && myTextFiled.getText().length()>0)
myTextFiled.setText(myTextFiled.getText().substring(0, myTextFiled.getText().length()-1));
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
};
//to null out handling other inputs
myTextFiled.setInputMap(JTextField.WHEN_FOCUSED, new InputMap());
//to add your own handling
myTextFiled.addKeyListener(myKeyListner);
Note: You have to add handling to insert/remove from the pointer's position.
Regards,
Use a custom Document:
public class NumericDocument extends PlainDocument {
#Override
public void insertString(int pos, String text, AttributeSet as)
throws BadLocationException {
try {
Integer.parseInt(text);
super.insertString(pos, text, as);
} catch(NumberFormatException e) {
Toolkit.getDefaultToolkit().beep();
}
}
}
Install to your TextField:
JtextField field = new JTextField();
field.setDocument(new NumericDocument());
This will work, even if text is pasted (where no KeyEvent is fired).
Related
In java , i am trying to make simple currency converter, but for that i need a text field which can restrict input to numbers only and more importantly double numbers. I tried using JFormatedTextField but it only format the input after you have done your input and click elsewhere but i need to restrict TextField to consume() each invalid character while doing input.
Possible Attempts:
Using JFormatedTextField:
JFormatedTextField textField = new JFormatedTextField(new DoubleFormat());
textField.setBounds(190, 49, 146, 33);
frame.getContentPane().add(textField);
textField.setColumns(10);
Using KeyTyped Event:
char c = arg0.getKeyChar();
if(!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c== KeyEvent.VK_DELETE)){
arg0.consume();
}
Using KeyTyped Event with regex:
if(!((textField.getText().toString+arg0.getKeyChar()).matches("[0-9]*(.[0-9]*)?"))){
arg0.consume();
}
Second and third attempt were close but then second attempt failed on point values and third attempt always read first character on textField no matter what it is, So any suggestions ? i am not very fond of JAVA GUI so kindly be patient.
If you know how many places before and after decimal point you want, you can also use MaskFormatter. For example:
JFormattedTextField field = new JFormattedTextField(getMaskFormatter("######.##"));
(...)
private MaskFormatter getMaskFormatter(String format) {
MaskFormatter mask = null;
try {
mask = new MaskFormatter(format);
mask.setPlaceholderCharacter('0');
}catch (ParseException ex) {
ex.printStackTrace();
}
return mask;
}
However it will chenge a look of JTextField, so it will be always visible 000000.00 in it.
EDIT
Another way, not too elegant, but in my opinion working. Try with DecumentListener, maybe it will suit your needs:
field = new JFormattedTextField();
field.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
Runnable format = new Runnable() {
#Override
public void run() {
String text = field.getText();
if(!text.matches("\\d*(\\.\\d{0,2})?")){
field.setText(text.substring(0,text.length()-1));
}
}
};
SwingUtilities.invokeLater(format);
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
I used regex: \\d*(\\.\\d{0,2})? because two decimal places is enough for currency.
You would need to use a DocumentFilter. Read the section from the Swing tutorial on Implementing a DocumentFilter for an example to get you started.
Your implementation will be more complex because you will need to take the text already in the Document and then insert the new text in the appropriate location in the String and then invoke Double.parseDouble(...) on the String to make sure it is a valid double value.
If the validation succeeds then you continue with the insertion otherwise you can generate beep.
You can add a key listener to the text field and implement the keyReleased() method to determine if they value in the text field is a double after every key stroke by the user.
public class CurrencyJTF extends JFrame {
JButton jButton = new JButton("Unfocus");
final JFormattedTextField textField = new JFormattedTextField(new DecimalFormat());
double lastDouble = 0.0;
public CurrencyJTF() throws HeadlessException {
textField.setColumns(20);
textField.setText(lastDouble + "");
this.setLayout(new FlowLayout());
this.add(textField);
this.add(jButton);
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
handleKeyReleased();
}
});
}
private void handleKeyReleased() {
String text = textField.getText();
if (text.isEmpty()) return;
try {
lastDouble = Double.parseDouble(text);
} catch (NumberFormatException ex) {
textField.setText(lastDouble + ""); // or set to other values you want
}
}
public static void main(String[] args) {
JFrame frame = new CurrencyJTF();
frame.setVisible(true);
frame.pack();
}
}
You can write your own KeyListener something like that:
public class DoubleNumbersKeyListener implements KeyListener {
final HashSet<Character> valid_keys = new HashSet<>();
final ArrayList<Character> sequence = new ArrayList<>();
public DoubleNumbersKeyListener() {
valid_keys.add('.');
valid_keys.add('0');
valid_keys.add('1');
valid_keys.add('2');
valid_keys.add('3');
valid_keys.add('4');
valid_keys.add('5');
valid_keys.add('6');
valid_keys.add('7');
valid_keys.add('8');
valid_keys.add('9');
valid_keys.add((char) KeyEvent.VK_BACK_SPACE);
valid_keys.add((char) KeyEvent.VK_DELETE);
}
#Override
public void keyTyped(KeyEvent event) {
char c = event.getKeyChar();
if (!valid_keys.contains(c)) {
event.consume();
} else {
if (c == KeyEvent.VK_DELETE || c == KeyEvent.VK_BACK_SPACE) {
if (!sequence.isEmpty()) {
char last = sequence.remove(sequence.size() - 1);
if (last == '.') {
valid_keys.add(last);
}
}
} else {
sequence.add(c);
if (c == '.') {
valid_keys.remove(c);
}
}
}
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
Ive been trying a while and cant work out a way to get the text out of a textbox only after the barcode scanner has finished scanning. I am using Swing Framework and Java. My Code works if the text is pasted (Ctrl + V) into the JTextbox but the barcode scanner just does not work as my methods run for every couple of characters of the barcode in turn.
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
// warn();
}
public void removeUpdate(DocumentEvent e) {
// warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
input = textField.getText();
SwingUtilities.invokeLater(doUpdate);
}
});
Where input is a variable which I use
The doUpdate method which gets executed is here
final Runnable doUpdate = new Runnable() {
#Override
public void run() {
System.out.println(input + " Is being processed");
textField.setText("");
System.out.println(input.length());
lblStatus.setIcon(new ImageIcon(Main.class
.getResource("/com/daniel/status2.png")));
// frame.getContentPane().add(lblStatus2, BorderLayout.EAST);
if (input.length() <= 4) {
lblStatus.setIcon(new ImageIcon(Main.class
.getResource("/com/daniel/status3.png")));
return;
}
// TODO START
if (!content.containsKey(input)) {
content.put(input, "1");
} else {
Integer i = Integer.valueOf(content.get(input));
i++;
lblStatus.setIcon(new ImageIcon(Main.class.getResource(i
+ ".png")));
playSound(i + "");
if (i.equals(6)) {
i = 0;
}
content.put(input, String.valueOf(i));
}
System.out.println(content.get(input));
Properties properties = new Properties();
for (Entry<String, String> entry : content.entrySet()) {
properties.put((String) entry.getKey(), entry.getValue());
}
try {
properties.store(new FileOutputStream(path
+ "data.properties"), null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
All Im asking is how do I run a method with a String from the text box only after the barcode reader has finished
It's been a while since I used a barcode reader, but when I did each scan was a line. That is, each scan was a sequence of characters terminated by the new line character. So, you could test the input and only invoke doUpdate when you detect the new line character. That said, you might need to set a property on the text box to allow the new line character and remove it when detected.
You need someway to inject a delay between each update of the DocumentListener and the time your inspect/use the value from the text field.
A simple solution is to use a Swing Timer with a short delay (you can play around with this to find the threashold which is most useful to you). Each time the DocumentListener is notified, you simply reset the timer (start it again), so that it won't trigger until after the delay you specified has occurred, at which time you can read the text from the field.
public class TestPane extends JPanel {
private Timer updateTimer;
private JTextField field;
private JLabel label;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
updateTimer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setText(field.getText());
}
});
updateTimer.setRepeats(false);
label = new JLabel("...");
field = new JTextField(14);
field.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
processUpdate();
}
#Override
public void removeUpdate(DocumentEvent e) {
processUpdate();
}
#Override
public void changedUpdate(DocumentEvent e) {
processUpdate();
}
});
add(field, gbc);
add(label, gbc);
}
protected void processUpdate() {
updateTimer.restart();
}
}
You could test this using Robot, which can be used to inject key strokes into the event queue with a specified delay, or just run your scanner at it.
See How to use Swing Timers for more details
You should also attach a ActionListener to the field and see if the scanner triggers the ActionListener, which would be a simpler solution over all
What is the best way to validate swing application's input fields such as text fields, comboboxes, etc and let the user to press Save button only if everything is ok. Assume that Search function also in the same interface. So searching for record will also fill up input fields. But Save button should remain disable in that case.
initComponents();
btnSave.setEnabled(false);
txt1.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
}
#Override
public void removeUpdate(DocumentEvent e) {
validate(txt1.getText(),e);
}
#Override
public void insertUpdate(DocumentEvent e) {
validate(txt1.getText(),e);
}
public void validate(String enteredText,DocumentEvent e) {
String currText = "";
try {
Document doc = (Document) e.getDocument();
currText = doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
}
if(enteredText.equals(currText)){
//if validated successfully
btnSave.setEnabled(false);
}else{
btnSave.setEnabled(true);
}
}
});
did you try like this?
final JTextField textField = new JTextField();
final JButton submitBtn = new JButton();
submitBtn.setEnabled(true);
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
validate(e);
}
public void removeUpdate(DocumentEvent e) {
validate(e);
}
public void insertUpdate(DocumentEvent e) {
validate(e);
}
public void validate(String enteredText) {
String currText = "";
try {
Document doc = (Document)e.getDocument();
currText = doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
//validation of currText here
//if validated successfully
submitBtn.setEnabled(true);
//else
submitBtn.setEnabled(false);
}
});
Condition the enabled property of your Save button using setEnabled() in two places:
In your implementation of shouldYieldFocus() in an InputVerifier attached to each relevant component. The tutorial and some examples are cited here.
In your component's normal listener.
Create a method to check if all the inputs are completed or/and all the validations are passed and finally return a boolean.
public boolean validate(...){
//some stuff
if(validated){
return true;
}else{
return false;
}
}
then you can use it like.
button.setEnabled(validate(...));
I am learning java swing. There is an editable JComboBox for selecting different depths of water and a JTextField to accept mobile number. My question is how can I restrict the user to enter only digits in these two fields and also, how to limit the maximum number of character inputs like not more than 10 for the mobile number? Are methods available for these requirements or I need to define them of my own?
Thanks in advance for your help.
Use a JFormattedTextField something like:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("JFormattedTextField Example");
MaskFormatter fmt = null;
// A phone number 10 digits
try {
fmt = new MaskFormatter("(###)-###-####");//brackets () are optional just there for my pref
fmt.setPlaceholderCharacter('*');//set place holder for the empty digits of the number
} catch (java.text.ParseException e) {
}
JFormattedTextField tft1 = new JFormattedTextField(fmt);
frame.add(tft1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
});
}
This automatically has the properties you want it will only accept digits in a specified format
Have a look at the docs too for more info: JFormattedTextField
How about this to restrict the user from typing characters other than numbers in phone text field
TF1.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
char k=arg0.getKeyChar();
if (!(k>='0' && k<='9'))
arg0.consume();
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
});
I have been trying with no luck to get a JFormattedTextField to highlight on mouse click. I have been able to get it to work fine while tabbing through fields, however I would like to highlight everything on clicking.
I am only able to highlight on mouse click if I click and hold for about 1.5-2 seconds on the text field; I have no idea why.
I've searched and tried a few fixes including extending the class;
class HFTextField extends JFormattedTextField
{
HFTextField(MaskFormatter formatter)
{
super(formatter);
}
#Override
protected void processFocusEvent(FocusEvent e)
{
super.processFocusEvent(e);
if (e.getID() == FocusEvent.FOCUS_GAINED)
{
this.selectAll();
}
}
}
I am also defining a (rather verbose!) FocusListener which uses SwingUtilities.invokelater;
public static FocusListener CreateHighlightTextFieldFocusListener(final JTextField text_field)
{
FocusListener fl =
new FocusAdapter()
{
public void focusGained(FocusEvent evt)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
text_field.selectAll();
}
});
}
};
return fl;
}
and this is the function that creates formatted text fields;
public static JTextField CreateFormattedTextField(int x, int y, int width, int height,
Method action_method, Method changed_method, Method remove_method,
Method update_method, String mask_formatter, String banned_chars)
{
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter(mask_formatter);
} catch (ParseException e) {
assert(false);
}
if(banned_chars != null)
formatter.setInvalidCharacters(banned_chars);
JTextField text_field = new HFTextField(formatter);
text_field.setBounds(x, y, width, height);
if(action_method != null)
{
text_field.addActionListener(CreateTextFieldActionListener(action_method, text_field));
}
text_field.getDocument().addDocumentListener(
CreateTextFieldDocumentListener(changed_method, remove_method,
update_method, text_field));
text_field.addFocusListener(CreateHighlightTextFieldFocusListener(text_field));
return text_field;
Any help would be greatly appreciated!
maybe you have got problems with EDT,
how method you use for/how you added value to JTextField
works with JTextField, JFormateddTextField, with JComboBox too, and with AutoCompleted funcionalies http://www.java2s.com/Code/Java/Swing-JFC/AutocompleteTextField.htm
private FocusListener focsListener = new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
dumpInfo(e);
}
#Override
public void focusLost(FocusEvent e) {
//dumpInfo(e);
}
private void dumpInfo(FocusEvent e) {
//System.out.println("Source : " + name(e.getComponent()));
//System.out.println("Opposite : " + name(e.getOppositeComponent()));
//System.out.println("Temporary: " + e.isTemporary());
Component c = e.getComponent();
if (c instanceof JFormattedTextField) {
((JFormattedTextField) c).requestFocus();
((JFormattedTextField) c).setText(((JFormattedTextField) c).getText());
((JFormattedTextField) c).selectAll();
} else if (c instanceof JTextField) {
((JTextField) c).requestFocus();
((JTextField) c).setText(((JTextField) c).getText());
((JTextField) c).selectAll();
}
}
private String name(Component c) {
return (c == null) ? null : c.getName();
}
};
Try the following code
yourTextField.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
yourTextField.selectAll();
}
});
}
});
I hate to give a simple answer, but have you tried using the MouseListener interface (or MouseAdapter class)?
Have you tried something like this:
fieldName.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
JTextComponent text = (JTextComponent) e.getSource();
text.selectAll();
}
});
Also, I would not recommend doing this asynchronously.
If you want specialized behavior for a mouse click, then add a MouseAdapter to your JTextFiled, and in the mouseClicked event handler, explicitly alter the background.
basically you can use this code (not sure that for each formatter and input masks), but for Number, Date and String you can use following, with ensure that this JFormattedTextField doesn't implements AutoCompleted
myTextField.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
myTextField.requestFocus();
myTextField.setText(myTextField.getText());
myTextField.selectAll();
}
#Override
public void focusLost(FocusEvent e) {
}
});
sure you can pack that into InvokeLate...