0

我正在使用 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("");
        }
     }
 }
4

7 回答 7

3

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

于 2013-12-20T02:48:17.230 回答
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;
        }
    }
}

一个完整的例子可以在这里找到。

编辑添加了一个如何用于InputVerifier限制数字输入的示例。你会想仔细检查正则表达式,但基本的想法就在那里......

于 2013-12-20T02:26:43.580 回答
2

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

  1. 如何使用格式化文本字段
  2. 实现文档过滤器

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

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

于 2013-12-20T02:48:52.410 回答
0

如果您尝试在无法转换为浮点数的字符串上调用 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
}
于 2013-12-20T02:25:59.543 回答
0

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

try {
 int number = Ineger.parseInt(inField.getText());
} catch (NumberFormatException e) {
//SHOW WARNING
}
于 2013-12-20T02:29:07.283 回答
0

你好朋友我给个建议

请在调用 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;

 }




 }
于 2013-12-20T04:25:13.243 回答
0
if (Label1.getText().matches("[0-9]+"))
// does Label1 containts numbers.
{
    // do math
}
else
{
    // warning
    Lavbel1.setText("");
}
于 2014-05-04T21:35:35.860 回答