作为一个在netbeans IDE中工作的java编程初学者,我做了一个货币转换器;我有一个'franc'的文本字段和另一个'euro'的文本字段,一个清除按钮用于清除两个文本字段,一个转换按钮和一个退出按钮用于离开窗口。我在转换按钮后面添加了代码,所以当它被按下时,转换应该被执行。然后我遇到了一些问题:当我运行程序并输入一个要转换的值时,转换不会发生,除非我先点击清除按钮,然后再输入值。现在我的问题是,我怎样才能防止程序这样做。或者说,如果无法做到这一点,有什么方法可以让我在程序启动时自动清除所有文本字段?谢谢你的帮助
以下是程序中处理事件的代码。
~ private void clear_buttonActionPerformed(java.awt.event.ActionEvent evt) {
euro_field.setText(" ");
franc_field.setText(" ");
}
private void quit_buttonActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void convert_buttonActionPerformed(java.awt.event.ActionEvent evt) {
double francVal, euroVal;
String a = franc_field.getText();
String b = euro_field.getText();
if(b.equals(" ") && !a.equals(" ")) {
francVal = Double.parseDouble(franc_field.getText());
euroVal = francVal/660.85;
euro_field.setText(String.valueOf(euroVal));
}
else if(a.equals(" ") && !b.equals(" ")) {
euroVal = Double.parseDouble(euro_field.getText());
francVal = euroVal*660.85;
franc_field.setText(String.valueOf(francVal));
}
}
// Variables declaration - do not modify
private java.awt.Button clear_button;
private java.awt.Button convert_button;
private javax.swing.JTextField euro_field;
private java.awt.Label euro_label;
private javax.swing.JTextField franc_field;
private java.awt.Label franc_label;
private java.awt.Button quit_button;
private java.awt.Label welcome_label;
// End of variables declaration ~
当一个 JTextField
是空的,其 getText()
方法返回一个空字符串,而不是包含一个空格的字符串。因此方法中的条件是 convert_buttonActionPerformed()
不见得是真的,但方法 clear_buttonActionPerformed()
实际上是在 JTextField
所以当你调用方法 convert_buttonActionPerformed()
之后 调用方法 clear_buttonActionPerformed()
那么,方法中的条件 convert_buttonActionPerformed()
为真。
改变方法 clear_buttonActionPerformed()
改为以下内容。
private void clear_buttonActionPerformed(java.awt.event.ActionEvent evt) {
euro_field.setText("");
franc_field.setText("");
}
并改变方法 convert_buttonActionPerformed()
到以下方面:
private void convert_buttonActionPerformed(java.awt.event.ActionEvent evt) {
double francVal, euroVal;
String a = franc_field.getText();
String b = euro_field.getText();
if(b.equals("") && !a.equals("")) {
francVal = Double.parseDouble(franc_field.getText());
euroVal = francVal/660.85;
euro_field.setText(String.valueOf(euroVal));
}
else if(a.equals("") && !b.equals("")) {
euroVal = Double.parseDouble(euro_field.getText());
francVal = euroVal*660.85;
franc_field.setText(String.valueOf(francVal));
}
}