Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Only integer jTextField?

843810Feb 20 2010 — edited Feb 20 2010
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
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
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!).
1 - 2
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Mar 20 2010
Added on Feb 20 2010
2 comments
182 views