处理非数字字符输入的更好方法

时间:2018-10-17 21:49:47

标签: java swing

当前正在研究一个基于GUI的小型Java / Swing项目,该项目涉及将值从一种度量转换为另一种度量。我对Swing也很陌生。

我一直在跟踪用户完成了多少次转换(“ calcCount”),但是无论用户是否抛出NumberFormatException,无论用户是否输入了非数字字符,计数都在增加-我将CalcCount设置为每当转换在try / Catch内失败时为零,这不应该发生吗? (如下)。

try {
conversionFieldValue = Double.parseDouble(text);
} catch (NumberFormatException e) {
  calcCount = 0;
  JOptionPane.showMessageDialog(null, "Error: the value entered may not be a valid number. \nPlease ensure that you are entering a valid double, with or without a decimal place.", "Conversion error", JOptionPane.ERROR_MESSAGE);
  conversionCountLabel.setText("Conversion Count: " + calcCount);
}

当前calcCount唯一要增加的地方是convertButton的侦听器,仅当输入的值不为空/空且源为convertButton时才触发。代码处理如下。

if(e.getSource() == convertButton && text.isEmpty() == false) {
   calcCount++;
   conversionCountLabel.setText("Conversion Count: " + calcCount);
}

我该如何更有效地处理此问题,并确保在正确的条件下calcCount实际上增加了-而不管解析是否失败?

编辑-----------------------

由于我未能解决我的问题,因此我在下面提供了一个小程序,该程序具有核心功能和我面临的问题:

“ thing1”类-驱动程序类:

import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JLabel;


public class thing1 {

    public static void main(String[] args) throws IOException {

        JFrame frame = new JFrame("Thing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        thing2 thing2 = new thing2();

        frame.getContentPane().add(thing2);

        frame.pack();
        frame.setVisible(true);
    }
}

“事物2”类,包括扩展和相关的侦听器

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


@SuppressWarnings("serial")
public class thing2 extends JPanel {

    /**
     *  Declaring all variables and components to be used within the GUI
     */
    private JTextField conversionField;
    private JLabel resultLabel, conversionCountLabel, inputLabel;
    private JButton convertButton, clearButton;
    private int calcCount;
    private String text;
    double conversionFieldValue;
    private double result;

    thing2() {

        /**
         * Creating two listeners which will be used
         * "convertListener" is used for conversions
         * "convertDeleteListener" is used to set the values of conversionField, resultLabel, conversionCountLabel and calcCount
         *  all used to display details about number of conversions etc.
         */
        ActionListener convertListener = new ConvertListener();
        ActionListener convertDeleteListener = new convertDeleteListener();

        /**
         *  Creating inputLabel and conversionCountLabel
         */
        inputLabel = new JLabel("Enter value:");
        conversionCountLabel = new JLabel("Conversion Count: ");

        /**
         *  Creating both the convertButon and clearButton
         *  Adding listeners to both buttons which determine when they are clicked,
         *  and what action should be carried out when done so.
         */
        convertButton = new JButton("Convert");
        convertButton.addActionListener(convertDeleteListener);
        convertButton.addActionListener(convertListener); // convert values when pressed
        clearButton = new JButton("Clear");

        /**
         *  Creating both the resultLabel and conversionField
         */
        resultLabel = new JLabel();
        conversionField = new JTextField(5);

        /**
         *  Adding all created assets to the JFrame.
         *  Adding toolTips to each of the created assets.
         *  Adding Listeners to select assets to carry out certain tasks.
         */
        add(inputLabel);
        add(conversionField);
        conversionField.addActionListener(convertListener);
        add(convertButton);
        add(resultLabel);
        add(conversionCountLabel);
        add(clearButton);
        clearButton.addActionListener(convertDeleteListener);

        /**
         *  Creating size of JFrame.
         *  Setting background colour.
         */
        setPreferredSize(new Dimension(800, 80));
        setBackground(Color.WHITE);
    }

    public class ConvertListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {

            /**
             *  Trimming all leading and trailing white spaces from the text the user has input.
             */
            text = conversionField.getText().trim();

            if (text.isEmpty() == false) {
                /**
                 *  Simply trying to convert input to a double, if that fails outputting a Dialog box to users screen stating why
                 */
                try {
                    conversionFieldValue = Double.parseDouble(text);
                } catch (NumberFormatException e) {
                    calcCount = 0;
                    JOptionPane.showMessageDialog(null, "Error: the value entered may not be a valid number. \nPlease ensure that you are entering a valid double, with or without a decimal place.", "Conversion error", JOptionPane.ERROR_MESSAGE);
                    conversionCountLabel.setText("Conversion Count: " + calcCount);
                }


                // the factor applied during the conversion
                double factor = 0;

                // the offset applied during the conversion.
                double offset = 0;

                // Setup the correct factor/offset values depending on required conversion

                result = factor * conversionFieldValue + offset;

                //formatting the value to two decimal places.
                String numAsString = String.format ("%.2f", result);
                resultLabel.setText(numAsString);
            } else {
                if(text.isEmpty() == true) {
                    /**
                     *  if the text value is empty, simply display a dialog box stating so
                     */
                    calcCount = 0;
                    JOptionPane.showMessageDialog(null, "Error: the text input area cannot be empty.", "Text area is empty...", JOptionPane.ERROR_MESSAGE);
                    conversionCountLabel.setText("Conversion Count: " + calcCount);
                }
            }
        }
    }

    public class convertDeleteListener implements ActionListener{
        public void actionPerformed(ActionEvent e){

            /**
             *  Using e.getSource to determine which button was pressed, doing some actions depending on which it was.
             */
            if(e.getSource() == convertButton && text.isEmpty() == false) {
                calcCount++;
                conversionCountLabel.setText("Conversion Count: " + calcCount);
            } else 
                if(e.getSource() == clearButton) {
                    calcCount = 0;
                    conversionField.setText("");
                    resultLabel.setText("");
                    conversionCountLabel.setText("Conversion Count: " + calcCount);
                } 

        }
    }
}

应该能够按原样进行编译,并且如果您在双精度字段以外的字段中输入任何字符,则会出现一个错误对话框-但是您会注意到即使转换失败,“ caclCount”仍然会增加。由于必须切掉所有转换的巨大开关,结果将显示为00.00-这在完整程序中可以正确计算,只是calcCount我遇到了问题。

编辑:现在,此问题已解决,感谢大家的帮助:)。

0 个答案:

没有答案