我在使用setText(“”)方法清除TextField时遇到问题。我正在尝试检查是否可以在图块中输入特定值,如果不能输入,则只想将其设置为空白。如果我在此放置任何其他值,它实际上会起作用,所以我认为这不是逻辑问题吗?仅当我想将其设置为空白时才起作用。
瓷砖类别
这是发生问题的类。
package com.company;
import javafx.application.Platform;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import static com.company.Game.TILE_SIZE;
public class Tile extends StackPane {
private int x;
private int y;
private static int[][] tab = new int[][]
{
{0, 8, 0, 0, 0, 0, 0},
{0, 0, 0, 5, 0, 0, 0},
{0, 11, 0, 0, 0, 0, 8},
{0, 0, 10, 0, 7, 0, 0},
{0, 9, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 6, 0},
{0, 11, 0, 0, 0, 7, 0},
{0, 0, 10, 0, 0, 0, 6}
};
private Utility utility = new Utility();
private Rectangle border = new Rectangle(TILE_SIZE - 8, TILE_SIZE - 8);
public TextField text = new TextField();
public Tile(int x, int y) {
Utility utility= new Utility();
this.x = x;
this.y = y;
border.setStroke(Color.BLACK);
text.setStyle("-fx-text-inner-color: black;" +
"-fx-control-inner-background: green;"
+"-fx-display-caret: false;");
text.setTextFormatter (new TextFormatter<Integer>(c -> {
if (c.getControlNewText().matches("^\\d{1,2}")) {
return c ;
} else {
return null ;
}
}));
text.focusedProperty().addListener((arg0, oldValue, newValue) ->
{
if (!newValue) {
if (text.getText().length() > 0)
{
String cos = text.getText();
int cos2 = Integer.parseInt(cos);
if(utility.isWon(tab))
{
Platform.exit();
System.exit(0);
}
else
{
if (!utility.isMoveValid(tab, this.y, this.x, cos2))
{
text.setText(""); //it works if it's not a blank string
} else {
tab[this.y][this.x] = cos2;
}
}
}
}
});
text.setFont(Font.font(50));
getChildren().addAll(border, text);
setTranslateX(this.x*TILE_SIZE);
setTranslateY(this.y*TILE_SIZE);
}
}
过滤器本身是接受UnaryOperator
对象的TextFormatter.Change
。它应该返回一个TextFormatter.Change
对象,其中包含实际的(过滤后的)更改。返回null会拒绝更改。
您将格式过滤器定义为需要匹配"^\\d{1,2}"
,该匹配将不匹配空字符串""
,因此它将不允许将文本字段设置为空字符串:
text.setTextFormatter (new TextFormatter<Integer>(c -> { if (c.getControlNewText().matches("^\\d{1,2}")) { return c ; } else { return null ; } }));
您需要修复匹配的正则表达式,以允许使用空字符串,或者提供其他解决方案以允许字段中使用空字符串值。例如:
text.setTextFormatter (new TextFormatter<Integer>(c -> { String newText = c.getControlNewText(); if ("".equals(newText) || newText.matches("^\\d{1,2}")) { return c ; } else { return null ; } }));