JavaFX中按键事件实现两数自动相加未达预期效果
Hey there, let's figure out why your sum calculation isn't working as expected when typing into the Number2 TextField. I'll walk through the most likely issues and how to fix them:
1. Double-Check FXML Event Binding
First off, make sure you've properly linked the Total method to Number2's keypress event in your FXML file. Without this connection, the method will never fire when you type. Your FXML should have something like this for the Number2 TextField:
<TextField fx:id="Number2" onKeyPressed="#Total" />
If this line is missing, that's probably the first thing to fix.
2. Timing Problem with KEY_PRESSED Event
The KEY_PRESSED event triggers before the character is actually added to the TextField. That means when you call Number2.getText() in your Total method, you're getting the text that was there before you pressed the key—so your sum will always be one step behind.
A quick fix here is to use the KEY_RELEASED event instead, since it fires after the character has been entered. Update your FXML to:
<TextField fx:id="Number2" onKeyReleased="#Total" />
3. Unhandled NumberFormatException
Another big issue: if either Number1 or Number2 is empty, or contains non-numeric characters, Integer.parseInt() will throw a NumberFormatException. This crashes the method before it can update the total TextField.
Let's add error handling to your Total method to handle these cases:
@FXML void Total(KeyEvent event) { try { // Handle empty inputs by treating them as 0 int num1 = Number1.getText().isEmpty() ? 0 : Integer.parseInt(Number1.getText()); int num2 = Number2.getText().isEmpty() ? 0 : Integer.parseInt(Number2.getText()); total.setText(String.valueOf(num1 + num2)); } catch (NumberFormatException e) { // If non-numeric input is entered, set total to 0 (or show a message if you prefer) total.setText("0"); // Optional: print the error to debug what went wrong // e.printStackTrace(); } }
Bonus: Better Approach with JavaFX Bindings
For real-time updates like this, JavaFX's built-in binding system is way more reliable and cleaner than handling key events manually. It automatically updates the total whenever either input changes, no event handlers needed. Here's how to implement it:
Add this code to your controller's initialize() method (make sure your controller implements Initializable):
import javafx.beans.binding.Bindings; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.fxml.Initializable; import java.net.URL; import java.util.ResourceBundle; public class YourController implements Initializable { @FXML private TextField Number1; @FXML private TextField Number2; @FXML private TextField total; @Override public void initialize(URL url, ResourceBundle resourceBundle) { // Create integer properties to bind to our text fields IntegerProperty num1Property = new SimpleIntegerProperty(); IntegerProperty num2Property = new SimpleIntegerProperty(); // Bind num1Property to Number1's text, converting to int (default to 0 if invalid) num1Property.bind(Bindings.createIntegerBinding(() -> { try { return Integer.parseInt(Number1.getText()); } catch (NumberFormatException | NullPointerException e) { return 0; } }, Number1.textProperty())); // Do the same for num2Property and Number2 num2Property.bind(Bindings.createIntegerBinding(() -> { try { return Integer.parseInt(Number2.getText()); } catch (NumberFormatException | NullPointerException e) { return 0; } }, Number2.textProperty())); // Bind the total TextField's text to the sum of the two properties total.textProperty().bind(Bindings.convert(num1Property.add(num2Property))); } }
With this setup, the total will update instantly whenever either input changes—no need to handle key events at all, and it gracefully handles empty or invalid inputs.
内容的提问来源于stack exchange,提问作者Santosh

