Forum Stats

  • 3,875,869 Users
  • 2,266,977 Discussions
  • 7,912,360 Comments

Discussions

Only integer jTextField?

843810
843810 Member Posts: 46,938
edited Feb 20, 2010 9:40PM in Java Desktop Applications
Hi,

I have a JTextField and it should accept only integers.
I wrote some code and there is a beep voice when user press the not integer characters.But I want to filter the non integer character i mean i just want to see integers in the text field

here is the code please help me thanks.
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import
java.awt.event.KeyEvent;
import javax.swing.JTextField;

import
javax.swing.WindowConstants;
import javax.swing.SwingUtilities;

public
class onlyInteger extends javax.swing.JFrame {
private
JTextField jTextField1;

public static void main(String[]
args) {
SwingUtilities.invokeLater(new Runnable() {

public void run() {
onlyInteger inst = new
onlyInteger();
inst.setLocationRelativeTo(null);

inst.setVisible(true);
}
});

}

public onlyInteger() {
super();

initGUI();
}

private void initGUI() {

try {

setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

{
jTextField1 = new JTextField();

getContentPane().add(getJTextField1(), BorderLayout.NORTH);

jTextField1.setPreferredSize(new java.awt.Dimension(100,
28));
jTextField1.setSize(100, 28);

jTextField1.addKeyListener(new KeyAdapter() {

public void keyPressed(KeyEvent evt) {

jTextField1KeyPressed(evt);
}

});
}
pack();
setSize(400,
300);
} catch (Exception e) {

e.printStackTrace();
}
}

public
JTextField getJTextField1() {
return jTextField1;
}
private void jTextField1KeyPressed(KeyEvent evt) {


int k=evt.getKeyCode();
if(k<48||k>57)

{getToolkit().beep();
/* WHAT SHOULD I WRITE HERE?*/
}

}

}



Thank you

Comments

  • darrylburke
    darrylburke Member Posts: 18,007
    1. Use code tags to post codes -- [code]CODE[/code] will display as
    CODE
    Or click the CODE button and paste your code between the {code} tags that appear.

    2. Use a DocumentFilter, not a KeyListener.

    db
  • User_64CKJ
    User_64CKJ Member Posts: 7,279 Silver Badge
    BilgehanP wrote:
    ..I have a JTextField and it should accept only integers.
    It 'sounds' as though this might be better done using a JSpinner with a NumberModel, than beeping at the end user every time they hit a key that does not fit (yuck!).
This discussion has been closed.