Java Swing JTextField - 仅限数字

 我系懒懒懒猫 发布于 2023-02-08 11:42

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

这是我的代码:

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("
" + Integer.toString(Integer.parseInt(deg.getText()) * 9 / 5 + 32) + "o F"); } else if (ftoc.isSelected() == true) { result.setText("
" + Integer.toString((Integer.parseInt(deg.getText()) - 32) * 5 / 9) + "o C"); } else { result.setText("
Error."); } } 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("o"); 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); } } }

我想限制JTextField deg只有整数.有什么方法可以做到吗?

任何帮助,将不胜感激!

2 个回答
  • 你只需要转换你的 -

    JTextField deg;
    

    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
    

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

    谢谢

    2023-02-08 11:45 回答
  • "我想将JTextField deg限制为只有整数."

    试试这个.使用文档过滤器

    ((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);
                }
            });
    

    2023-02-08 11:45 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有