【问题标题】:show warning if users enter letter instead number in java applet如果用户在 java 小程序中输入字母而不是数字,则显示警告
【发布时间】:2013-12-20 02:18:05
【问题描述】:

我正在用 GUI 在 java 小程序中编写一个小费计算器应用程序,我的问题是如何确保如果用户输入字母而不是数字时会弹出错误消息

这是我第一次提问,请多多关照!谢谢!!!

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

// Typing in the text field and hitting return adds text to text area.
// Clicking on button erases the text area.
public class TextApplet extends Controller implements ActionListener 
{
    private static final int ROWS = 1; // rows in TextArea
    private static final int COLS = 10; // cols in text field & area

    private String amount;
    private float number;
    private JTextField inField, output;         // Input field

    private JButton clear, calc;     
         // button to clear output


    public void begin() 
    {

        Container contentPane = getContentPane();
        JPanel topPanel = new JPanel();       // prepare text field & label
        JLabel inLabel = new JLabel("Bill Cost: ");
        inField = new JTextField(COLS);

        inField.addActionListener(this);
        JLabel topTitle = new JLabel("Tip Calculator", JLabel.CENTER);
        JPanel combinePanel = new JPanel();

        combinePanel.add ( inLabel );
        combinePanel.add ( inField );
        JPanel combinePanel1 = new JPanel();
        combinePanel1.add ( topTitle );

        topPanel.add ( combinePanel1 );
        topPanel.add ( combinePanel );


        topPanel.setLayout ( new GridLayout ( 3,1) );
        contentPane.add(topPanel,BorderLayout.NORTH);

        JPanel centerPanel = new JPanel();     // prepare text area & label
        JLabel outLabel = new JLabel("Bill + Tip:");
        output = new JTextField(COLS);
        output.setEditable(false);        // Prevent user from wrting in output
        centerPanel.add(outLabel);
        centerPanel.add(output);
        contentPane.add(centerPanel,BorderLayout.CENTER);

        JPanel bottomPanel = new JPanel(); 

        // create button
        clear = new JButton("  Clear  ");
        calc = new JButton("Calculate");
        calc.addActionListener(this);
        clear.addActionListener(this);
        bottomPanel.add(calc);
        bottomPanel.add(clear);

        contentPane.add(bottomPanel,BorderLayout.SOUTH);
        validate();
    }

    // add text to area if user hits return, else erase text area
    public void actionPerformed(ActionEvent evt) 
    {
        if (evt.getSource() == calc )
        { 
            amount = inField.getText();
            number = ( Float.parseFloat( amount ) );
            number = (15*number/100);

            output.setText ( Float.toString ( number ) + '$' );
        }

        else if (evt.getSource() == clear )
        {
            output.setText("$");
            inField.setText("");
        }
     }
 }

【问题讨论】:

    标签: java swing applet appletviewer


    【解决方案1】:

    您可以通过多种方式实现这一目标,您可以使用

    【讨论】:

    • +1 用于 JSpinner。我总是忘记那个。
    • @camickr 认为您通常说得更好;)
    【解决方案2】:

    看看javax.swing.InputVerifier。这可以很容易地附加到JTextField

    JTextField inputField = new JTextField();
    inputField.setInputVerifier(new NumericInputVerifier());
    
    private class NumericInputVerifier extends InputVerifier
    {
        @Override
        public boolean verify(JComponent input)
        {
            if (((JTextField) input).getText().matches("[0-9]+"))
            {
                return true;
            }
            else
            {
                JOptionPane.showMessageDialog(input, "Only numbers are allowed", "Warning", JOptionPane.WARNING_MESSAGE);
                return false;
            }
        }
    }
    

    可以在这里找到完整的example

    编辑添加了如何使用InputVerifier 限制数字输入的示例。您需要仔细检查正则表达式,但基本思想就在那里......

    【讨论】:

    • InputVerifier 只是不允许用户离开文本字段。它仍然会让他们提交无效条目并引发操作事件。
    • 同意。如果这不符合 OP 的要求,那么还有其他方法可以解决这个问题(如其他答案中所述)。我也喜欢使用JFormattedTextField。这已在问题Best way to constrain user to enter a time in a JTextField 中讨论过
    【解决方案3】:

    使用 JFormattedTextField 或 DocumentFilter。然后用户甚至无法输入非数字数字。见:

    1. How to Use Formatted Text Fields
    2. Implementing a Document Filter

    对于文档过滤器,您需要在输入时检查每个字符以确保它是数字。

    最好在用户键入时进行类似的简单编辑,而不是等到您单击按钮进行处理。

    【讨论】:

      【解决方案4】:

      朋友你好,给个建议

      请在调用actionPerformed方法时添加验证

       public void actionPerformed(ActionEvent evt) 
      {
          if (evt.getSource() == calc )
          { 
             if(validate()){
              amount = inField.getText();
              number = ( Float.parseFloat( amount ) );
              number = (15*number/100);
      
              output.setText ( Float.toString ( number ) + '$' );
      
              }
           else{
         // show message for inter valid number or any other
             }
           }
      
          else if (evt.getSource() == clear )
          {
              output.setText("$");
              inField.setText("");
          }
       }
        boolean validate(){  
      
         try{
          amount = inField.getText();
              number = ( Float.parseFloat( amount ) );
            return true;
      
        }
         catch(Exception e){
         return false;
      
       }
      
      
      
      
       }
      

      【讨论】:

        【解决方案5】:

        如果您尝试在无法转换为浮点数的字符串上调用 Float.parseFloat,它将抛出 NumberFormatException。您需要捕获此异常。

        try {        
        number = ( Float.parseFloat( amount ) );
        number = (15*number/100);
        
        output.setText ( Float.toString ( number ) + '$' );
        } catch(NumberFormatException e) {
        //code to show error message here
        }
        

        【讨论】:

          【解决方案6】:

          考虑到,您必须将字符串转换为整数才能进行数学运算,您可以这样做:

          try {
           int number = Ineger.parseInt(inField.getText());
          } catch (NumberFormatException e) {
          //SHOW WARNING
          }
          

          【讨论】:

            【解决方案7】:
            if (Label1.getText().matches("[0-9]+"))
            // does Label1 containts numbers.
            {
                // do math
            }
            else
            {
                // warning
                Lavbel1.setText("");
            }
            

            【讨论】:

            • 这适用于应用程序,非常简单。
            猜你喜欢
            • 1970-01-01
            • 2022-12-17
            • 2021-12-14
            • 1970-01-01
            • 1970-01-01
            • 2016-08-13
            • 2015-04-14
            • 2021-11-14
            • 2015-12-24
            相关资源
            最近更新 更多