java 在java应用程序中仅在文本字段中输入数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26944185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
input in text field only number in java application
提问by Brownman Revival
DishFormPanelistIdLbl.setText("Panelist ID:");
DishFormPanelistIdTxt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DishFormPanelistIdTxtActionPerformed(evt);
}
});
I have here a text label and text field for ID i want to input only numbers in text how is it possible?been trying the sample program un net beans but they dont have such a solution for this problem any help is appreciated
我在这里有一个文本标签和 ID 文本字段我只想在文本中输入数字怎么可能?一直在尝试示例程序 un net beans 但他们没有解决这个问题的任何帮助表示赞赏
"Update"
"Update"
What i want here is when i type letter nothing will show but when number then it will show
我想要的是当我输入字母时什么都不会显示但是当数字时它会显示
回答by Brownman Revival
What i did is in the design mode i right click the text field > Events > Key > KeyTyped
我所做的是在设计模式下我右键单击文本字段> 事件> 键> KeyTyped
then in the code i hade something like this
然后在代码中我有这样的事情
private void DishFormPanelistIdTxtKeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
char enter = evt.getKeyChar();
if(!(Character.isDigit(enter))){
evt.consume();
}
}
i didnt get the solution here in stack but i will link it this is the link
我没有在堆栈中找到解决方案,但我会链接它,这是链接
回答by Vince Emigh
You could do this by using a JFormattedTextField
. It's pretty straight forward: you pass it a formatter (which extends AbstractFormatter
), and the formatter will allow you to restrict and modify how things are displayed in your field. In this case, you could use the pre-made formatter NumberFormatter
:
您可以通过使用JFormattedTextField
. 这非常简单:您向它传递一个格式化程序(它扩展了AbstractFormatter
),格式化程序将允许您限制和修改内容在您的字段中的显示方式。在这种情况下,您可以使用预制的格式化程序NumberFormatter
:
NumberFormatter formatter = new NumberFormatter(); //create the formatter
formatter.setAllowsInvalid(false); //must specify that invalid chars are not allowed
JFormattedTextField field = new JFormattedTextField(formatter); //pass the formatter to the field
This will also add a comma where ever needed (for example, when you type in 1000, it'll display it as 1,000
.
这也会在需要的地方添加一个逗号(例如,当您输入 1000 时,它会显示为1,000
.