您好,我想要一个文本字段,其中用户只能输入数字,而不能输入字符。我很困惑,因为有些人想用 Action 监听器来完成,有些人想用格式化程序和更多选项来完成。有人能告诉我该怎么做吗?以及将它放在代码中的哪个位置,它总是检查是否有字母并自动删除它?谢谢
package sample;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import java.awt.*;
import java.util.function.UnaryOperator;
public class Controller {
GuessingGame gg = new GuessingGame();
//Main m = new Main();
public Button playButton;
public Button settingsButton;
public Button exitButton;
public TextField textfield;
public Label countText;
public Label notification;
public int currentNumber = 0;
public int numberBetweenLower = 0;
public int numberBetweenHigher = 100;
public void clickedOnExit() {
System.exit(1);
}
;
public void clickedOnSettings() {
}
;
public void clickedOnPlay() {
Main.pStage.setScene(Main.scene2);
}
;
public void clickedBackToMenu() {
Main.pStage.setScene(Main.scene1);
}
;
public void enteredTextfield() {
currentNumber = Integer.parseInt(textfield.getText());
textfield.clear();
GuessingGame.Result checkNumber;
checkNumber = gg.evaluateEnteredNumber(currentNumber);
if (checkNumber == GuessingGame.Result.HIGHER) {
notification.setText("HIGHER");
}
;
if (checkNumber == GuessingGame.Result.LOWER) {
notification.setText("LOWER");
}
;
if (checkNumber == GuessingGame.Result.EQUALS) {
notification.setText("YOU GOT IT!");
}
;
countText.setText("" + gg.getCounter());
}
@FXML
public void initialize() {
// initialize controller and set text shown in the UI
}
private static final class NumberFormatUnaryOperator implements UnaryOperator<TextFormatter.Change> {
/**
* Applies this function to the given argument.
*
* @param change the function argument
* @return the function result
*/
@Override
public TextFormatter.Change apply(TextFormatter.Change change) {
var String = change.getControlNewText();
if (!text.matches("\\d*")) {
Toolkit.getDefaultToolkit().beep();
return null;
}
return change;
}
}
}
最佳答案
我个人更喜欢Formatter方式,使用起来非常简单。
例如:
public class TodoListController implements Initializable {
@FXML
public TextField input;
@Override
public void initialize(final URL url, final ResourceBundle resourceBundle) {
input.setTextFormatter(new TextFormatter<>(new NumberFormatUnaryOperator()));
}
private static final class NumberFormatUnaryOperator implements UnaryOperator<TextFormatter.Change> {
/**
* Applies this function to the given argument.
*
* @param change the function argument
* @return the function result
*/
@Override
public TextFormatter.Change apply(TextFormatter.Change change) {
String text = change.getControlNewText();
if (!text.matches("\\d*")) {
Toolkit.getDefaultToolkit().beep();
return null;
}
return change;
}
}
}
上面的代码根本阻止输入任何字符...
您还可以使用监听器方式,实际上这两种方法都非常适合您要解决的问题。此外,就JavaFX API而言,格式化程序正是针对此类用例而设计的。请随意在您的代码中使用它
关于java - 如何直接消除文本字段JavaFx中的字符以使用户无法输入字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60000811/