Java Swing JTextField - 只有数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20768653/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:11:53  来源:igfitidea点击:

Java Swing JTextField - Only Numbers

javaswingvalidationjtextfieldtemperature

提问by Oliver Ni

I am making a small java Swing Applet that converts temperatures: TempConvert.java

我正在制作一个转换温度的小型 java Swing Applet:TempConvert.java

Here is my code:

这是我的代码:

package swing;

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

/** Celcius to Fahrenheit Converter
 * @version 1.0
 * @author Oliver Ni
 */

public class TempConvert extends JApplet{
    JLabel result;
    JRadioButton ctof;
    JRadioButton ftoc;
    JTextField deg;
    JLabel degLab;
    JButton convert;

    public void convert() {
        if (ctof.isSelected() == true) {
            result.setText("<html><br>" + Integer.toString(Integer.parseInt(deg.getText()) * 9 / 5 + 32) + "<sup>o</sup> F</html>");
        } else if (ftoc.isSelected() == true) {
            result.setText("<html><br>" + Integer.toString((Integer.parseInt(deg.getText()) - 32) * 5 / 9) + "<sup>o</sup> C</html>");
        } else {
            result.setText("<html><br>Error.</html>");
        }
    }

    public void makeApplet() {
        setLayout(new FlowLayout());
        ctof = new JRadioButton("Celcius to Fahrenheit");
        ftoc = new JRadioButton("Fahrenheit to Celcius");
        convert = new JButton("Convert");
        result = new JLabel("");
        ButtonGroup group = new ButtonGroup();
        group.add(ctof);
        group.add(ftoc);

        deg = new JTextField(10);
        degLab = new JLabel("<html><sup>o</sup></html>");
        convert.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                convert();
            }
        });
        add(ctof);
        add(ftoc);
        add(deg);
        add(degLab);
        add(convert);
        add(result);
    }

    public void init() {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    makeApplet();
                }
            });
        } catch(Exception e) {
            System.out.println("Error loading because " + e);
        }
    }
}

I want to restrict the JTextFielddegto only integers. Is there any way I can do that?

我想限制JTextFielddeg为只有整数。有什么办法可以做到吗?

Any help would be appreciated!

任何帮助,将不胜感激!

采纳答案by Neelam Sharma

You just need to convert your -

你只需要转换你的 -

JTextField deg;

to

NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault());
DecimalFormat decimalFormat = (DecimalFormat) numberFormat;
decimalFormat.setGroupingUsed(false);
deg = new JFormattedTextField(decimalFormat);
deg.setColumns(15); //whatever size you wish to set

This will return a general-purpose number format for the current default locale.

这将返回当前默认语言环境的通用数字格式。

Thanks

谢谢

回答by Paul Samsotha

"I want to restrict the JTextField deg to only integers."

“我想将 JTextField deg 限制为仅整数。”

Try this. Use a Document Filter

尝试这个。使用文档过滤器

((AbstractDocument) deg.getDocument()).setDocumentFilter(new DocumentFilter() {
            Pattern regEx = Pattern.compile("\d+");

            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                Matcher matcher = regEx.matcher(text);
                if (!matcher.matches()) {
                    return;
                }
                super.replace(fb, offset, length, text, attrs);
            }
        });

回答by AbhishekJoshi

For a simple program like this, you can try to use Formatted Text Fields: http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

对于这样的简单程序,您可以尝试使用格式化文本字段:http: //docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html