如果用户在java小程序中输入字母而不是数字,则显示警告
我正在用java小程序和GUI编写一个提示计算器应用程序,我的问题是,如果用户输入字母而不是数字,我如何确保错误消息会弹出 这是我第一次问问题,请对我宽容一点!谢谢如果用户在java小程序中输入字母而不是数字,则显示警告,java,swing,applet,appletviewer,Java,Swing,Applet,Appletviewer,我正在用java小程序和GUI编写一个提示计算器应用程序,我的问题是,如果用户输入字母而不是数字,我如何确保错误消息会弹出 这是我第一次问问题,请对我宽容一点!谢谢 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. // Click
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("");
}
}
}
如果尝试对无法转换为浮点的字符串调用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
}
看一看。可轻松附加到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;
}
}
}
在这里可以找到完整的文档
Edit添加了如何使用
InputVerifier
限制数字输入的示例。您可能想再次检查正则表达式,但基本思想是…考虑到这一点,您必须将字符串转换为整数才能进行计算,您可以这样做:
try {
int number = Ineger.parseInt(inField.getText());
} catch (NumberFormatException e) {
//SHOW WARNING
}
有很多方法可以实现这一点,你可以使用
- 一个
- A
- A
- 或者
最好是在用户键入时进行简单的编辑,而不是等到单击按钮后再进行处理。你好,朋友,我将给出一个建议 请在调用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;
}
}
InputVerifier只是不允许用户离开文本字段。它仍将允许他们提交无效条目并导致操作事件。已同意。如果这不符合OP的要求,那么还有其他方法来解决这个问题(如其他答案所述)。我也喜欢使用
JFormattedTextField
。这已在JSpinner的问题+1中讨论过。“我总是忘了这件事。”卡米克认为你通常说得更好;)这是针对应用程序的,它非常简单。
if (Label1.getText().matches("[0-9]+"))
// does Label1 containts numbers.
{
// do math
}
else
{
// warning
Lavbel1.setText("");
}