我尝试编写密钥检测代码以提醒用户输入有效的密钥条目。如果键输入错误,则文本字段变为红色,并在更正时返回白色。出于某种原因,Eclipse无法识别VK_BACK_SPACE。这已经过时了吗?它仍然在KeyEvent的Oracle文档中。 使用它的代码行如下所示:
else if ( (event.getCharacter().compareTo("0") >= 0
&& event.getCharacter().compareTo("9") <= 0 )
|| (event.getKeyCode() == KeyEvent.VK_BACK_SPACE))
为什么getKeyCode和VK_BACK_SPACE都无法被识别?
我也遇到了颜色变化只发生过一次的问题。我正在使用KeyHandler,并在输入验证时,在红色和白色之间来回更改特定TextField的CSS样式。它仅在第一次输入无效输入时起作用,并且在输入被更正时拒绝返回白色背景。
代码如下所示:
EventHandler backgroundChanger = new EventHandler<KeyEvent>() {
public void handle(KeyEvent event) {
if ( (event.getCharacter().compareTo("a") >= 0
&& event.getCharacter().compareTo("z") <= 0)
|| (event.getCharacter().compareTo("A") >= 0
&& event.getCharacter().compareTo("Z") <= 0))
{
backgroundChangerWrong((TextField)event.getSource());
}
else if ( (event.getCharacter().compareTo("0") >= 0
&& event.getCharacter().compareTo("9") <= 0 ) )
{
Background originalColor = backgroundGrab.getBackground();
backgroundChangerRight((TextField)event.getSource(), originalColor);
}
else
{
backgroundChangerWrong((TextField)event.getSource());
}
}
};
TextField salaryField = new TextField();
salaryField.setPromptText("##.##");
gridPane.setConstraints(salaryField, 1, 0, 1, 1);
salaryField.getText();
salaryField.addEventFilter(KeyEvent.KEY_PRESSED, backgroundChanger);
gridPane.getChildren().add(salaryField);
后台更换器功能:
public static void backgroundChangerRight(TextField textObj, Background origBackground) {
textObj.setBackground(origBackground);
}
public static void backgroundChangerWrong(TextField textObj) {
textObj.setStyle("-fx-background-color: #ff0000;");
textObj.setOpacity(20);
}
CSS表格:
.text-field {
-fx-background-color: #ffffff, white, white;
-fx-border-color: grey;
-fx-border-width: 1;
-fx-border-radius: 1;
}
编辑: 进口:
import java.io.File;
import java.net.MalformedURLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;