我正在编写使用GUI的温度转换器。我将其设置为如果用户输入字符串或无效的温度,则在输入框下方显示错误标签。但是,该代码仍将像用户输入0一样进行处理。它将仍然输出转换。如何在下面的课程中阻止它这样做?
package gui;
import javax.swing.*;
import java.awt.*;
public class JDataInput
extends JPanel
{
private JLabel lblInput;
private JTextField txtInput;
private JLabel lblMessage;
public JDataInput()
{
}
public JDataInput(String caption)
{
lblInput = new JLabel(caption);
txtInput = new JTextField(20);
lblMessage = new JLabel("");
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
row1.add(lblInput);
row1.add(txtInput);
row2.add(lblMessage);
this.add(row1);
this.add(row2);
}
public double getDoubleValue()
{
double returnValue = 0;
lblMessage.setText(" ");
try
{
returnValue = Double.parseDouble(txtInput.getText());
}
catch (NumberFormatException nfex)
{
lblMessage.setText(nfex.toString());
lblMessage.setForeground(Color.RED);
}
return returnValue;
}
public double getIntValue()
{
int returnValue = 0;
lblMessage.setText(" ");
try
{
returnValue = Integer.parseInt(txtInput.getText());
}
catch (NumberFormatException nfex)
{
lblMessage.setForeground(Color.RED);
lblMessage.setText(nfex.toString());
}
return returnValue;
}
}
答案 0 :(得分:0)
从catch块中返回空值,例如
public double getDoubleValue()
{
double returnValue = 0;
lblMessage.setText(" ");
try
{
returnValue = Double.parseDouble(txtInput.getText());
}
catch (NumberFormatException nfex)
{
lblMessage.setText(nfex.toString());
lblMessage.setForeground(Color.RED);
return null;
}
return returnValue;
}
这将从函数中退出。