控制键盘输入到javafx文本字段
我想控制Javafx文本字段的输入,这样我就可以只允许数字输入,如果超过最大字符数,那么就不会对文本框进行任何更改 编辑:根据评论中的建议,我使用了JavaFX项目负责人建议的方法。阻止信件被输入非常有效。我只需要它也过滤特殊字符。我尝试将过滤器更改为(text.matchs(“[0-9]”),但这不允许输入退格 编辑2:找到了一个特殊字符和长度的过滤器。这是我的最终代码。谢谢你们的输入 以下是我创建的TextField类:控制键盘输入到javafx文本字段,java,javafx,Java,Javafx,我想控制Javafx文本字段的输入,这样我就可以只允许数字输入,如果超过最大字符数,那么就不会对文本框进行任何更改 编辑:根据评论中的建议,我使用了JavaFX项目负责人建议的方法。阻止信件被输入非常有效。我只需要它也过滤特殊字符。我尝试将过滤器更改为(text.matchs(“[0-9]”),但这不允许输入退格 编辑2:找到了一个特殊字符和长度的过滤器。这是我的最终代码。谢谢你们的输入 以下是我创建的TextField类: import javafx.scene.control.TextFie
import javafx.scene.control.TextField;
public class AttributeTextField extends TextField{
public AttributeTextField() {
setMinWidth(25);
setMaxWidth(25);
}
public void replaceText(int start, int end, String text) {
String oldValue = getText();
if (!text.matches("[a-z]") && !text.matches("[\\\\!\"#$%&()*+,./:;<=>?@\\[\\]^_{|}~]+")) {
super.replaceText(start, end, text);
}
if (getText().length() > 2 ) {
setText(oldValue);
}
}
public void replaceSelection(String text) {
String oldValue = getText();
if (!text.matches("[a-z]") && !text.matches("[\\\\!\"#$%&()*+,./:;<=>?@\\[\\]^_{|}~]+")) {
super.replaceSelection(text);
}
if (getText().length() > 2 ) {
setText(oldValue);
}
}
}
导入javafx.scene.control.TextField;
公共类AttributeTextField扩展了TextField{
公共AttributeTextField(){
设置最小宽度(25);
设置最大宽度(25);
}
公共void replaceText(int开始、int结束、字符串文本){
字符串oldValue=getText();
if(!text.matches(“[a-z]”)和&!text.matches(“[\\\\\!\”\\$%&()*+,./:;?@\\[\]^{124\}~]+”){
super.replaceText(开始、结束、文本);
}
如果(getText().length()>2){
setText(旧值);
}
}
公共选择(字符串文本){
字符串oldValue=getText();
if(!text.matches(“[a-z]”)和&!text.matches(“[\\\\\!\”\\$%&()*+,./:;?@\\[\]^{124\}~]+”){
super.replaceSelection(文本);
}
如果(getText().length()>2){
setText(旧值);
}
}
}
注意:我读过这篇文章,但这个解决方案对我不起作用。它只在输入数字后才会被激活。这意味着有人可以在框中键入字母文本,直到他们将焦点从文本字段移开为止。此外,他们可以输入大于允许值的数字,但不会在每个按键上进行验证s、 但是,在焦点转移(“更改”事件)之后。这是我的建议,两个事件过滤器可以是一个,在我的例子中,我在不同的情况下使用它们,这就是为什么有两个 以下是maxValueFilter(西班牙语xD),这是一个类:
public class FilterMaxValue implements EventHandler<KeyEvent> {
private int maxVal;
public FilterMaxValue (int i) {
this.maxVal= i;
}
public void handle(KeyEvent arg0) {
TextField tx = (TextField) arg0.getSource();
String chara = arg0.getCharacter();
if (tx.getText().equals(""))
return;
Double valor;
if (chara.equals(".")) {
valor = Double.parseDouble(tx.getText() + chara + "0");
} else {
try {
valor = Double.parseDouble(tx.getText() + chara);
} catch (NumberFormatException e) {
//The other filter will prevent this from hapening
return;
}
}
if (valor > maxVal) {
arg0.consume();
}
}
}
最终解决方案。不允许字母和特殊字符,并强制执行字符限制
import javafx.scene.control.TextField;
public class AttributeTextField extends TextField{
public AttributeTextField() {
setMinWidth(25);
setMaxWidth(25);
}
public void replaceText(int start, int end, String text) {
String oldValue = getText();
if (!text.matches("[A-Za-z]") && !text.matches("[\\\\!\"#$%&()*+,./:;<=>?@\\[\\]^_{|}~]+")) {
super.replaceText(start, end, text);
}
if (getText().length() > 2 ) {
setText(oldValue);
}
}
public void replaceSelection(String text) {
String oldValue = getText();
if (!text.matches("[A-Za-z]") && !text.matches("[\\\\!\"#$%&()*+,./:;<=>?@\\[\\]^_{|}~]+")) {
super.replaceSelection(text);
}
if (getText().length() > 2 ) {
setText(oldValue);
}
}
}
导入javafx.scene.control.TextField;
公共类AttributeTextField扩展了TextField{
公共AttributeTextField(){
设置最小宽度(25);
设置最大宽度(25);
}
公共void replaceText(int开始、int结束、字符串文本){
字符串oldValue=getText();
如果(!text.matches(“[A-Za-z]”)和&!text.matches(“[\\\\\!\”\\$%&()*+,./:;?@\\[\]^{124\}]+”){
super.replaceText(开始、结束、文本);
}
如果(getText().length()>2){
setText(旧值);
}
}
公共选择(字符串文本){
字符串oldValue=getText();
如果(!text.matches(“[A-Za-z]”)和&!text.matches(“[\\\\\!\”\\$%&()*+,./:;?@\\[\]^{124\}]+”){
super.replaceSelection(文本);
}
如果(getText().length()>2){
setText(旧值);
}
}
}
最好的方法是:
@FXML
private TextField txt_Numeric;
@FXML
private TextField txt_Letters;
@Override
public void initialize(URL url, ResourceBundle rb) {
/* add Event Filter to your TextFields **************************************************/
txt_Numeric.addEventFilter(KeyEvent.KEY_TYPED , numeric_Validation(10));
txt_Letters.addEventFilter(KeyEvent.KEY_TYPED , letter_Validation(10));
}
/* Numeric Validation Limit the characters to maxLengh AND to ONLY DigitS *************************************/
public EventHandler<KeyEvent> numeric_Validation(final Integer max_Lengh) {
return new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent e) {
TextField txt_TextField = (TextField) e.getSource();
if (txt_TextField.getText().length() >= max_Lengh) {
e.consume();
}
if(e.getCharacter().matches("[0-9.]")){
if(txt_TextField.getText().contains(".") && e.getCharacter().matches("[.]")){
e.consume();
}else if(txt_TextField.getText().length() == 0 && e.getCharacter().matches("[.]")){
e.consume();
}
}else{
e.consume();
}
}
};
}
/*****************************************************************************************/
/* Letters Validation Limit the characters to maxLengh AND to ONLY Letters *************************************/
public EventHandler<KeyEvent> letter_Validation(final Integer max_Lengh) {
return new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent e) {
TextField txt_TextField = (TextField) e.getSource();
if (txt_TextField.getText().length() >= max_Lengh) {
e.consume();
}
if(e.getCharacter().matches("[A-Za-z]")){
}else{
e.consume();
}
}
};
}
/*****************************************************************************************/
@FXML
私有文本字段txt_数字;
@FXML
私有文本字段txt_字母;
@凌驾
公共void初始化(URL、ResourceBundle rb){
/*将事件筛选器添加到文本字段**************************************************/
txt_Numeric.addEventFilter(KeyEvent.KEY_类型,数字_验证(10));
txt_Letters.addEventFilter(键入KeyEvent.KEY,字母验证(10));
}
/*数字验证将字符限制为最大长度,且仅限数字*************************************/
公共事件处理程序数字验证(最终整数最大长度){
返回新的EventHandler(){
@凌驾
公共无效句柄(KeyEvent e){
TextField txt_TextField=(TextField)e.getSource();
如果(txt_TextField.getText().length()>=max_Lengh){
e、 消费();
}
如果(e.getCharacter()匹配(“[0-9.]”){
如果(txt_TextField.getText()包含(“.”)和&e.getCharacter()匹配(“[.””){
e、 消费();
}如果(txt_TextField.getText().length()==0&&e.getCharacter().matches(“[.]”),则为else{
e、 消费();
}
}否则{
e、 消费();
}
}
};
}
/*****************************************************************************************/
/*字母验证将字符限制为maxLengh且仅限于字母*************************************/
公共事件处理程序字母验证(最终整数最大长度){
返回新的EventHandler(){
@凌驾
公共无效句柄(KeyEvent e){
TextField txt_TextField=(TextField)e.getSource();
如果(txt_TextField.getText().length()>=max_Lengh){
e、 消费();
}
如果(e.getCharacter()匹配(“[A-Za-z]”){
}否则{
e、 消费();
}
}
};
}
/*****************************************************************************************/
祝你好运。我只需设置“On Key Typed”事件来运行这个小过程:
@FXML public void processKeyEvent(KeyEvent ev) {
String c = ev.getCharacter();
if("1234567890".contains(c)) {}
else {
ev.consume();
}
}
它的工作原理类似于champ!我创建了一个自定义的文本字段,可以添加到Java Builder FX中(使用“导入JAR/FXML文件…”) 使用此文本字段可以设置
@FXML
private TextField txt_Numeric;
@FXML
private TextField txt_Letters;
@Override
public void initialize(URL url, ResourceBundle rb) {
/* add Event Filter to your TextFields **************************************************/
txt_Numeric.addEventFilter(KeyEvent.KEY_TYPED , numeric_Validation(10));
txt_Letters.addEventFilter(KeyEvent.KEY_TYPED , letter_Validation(10));
}
/* Numeric Validation Limit the characters to maxLengh AND to ONLY DigitS *************************************/
public EventHandler<KeyEvent> numeric_Validation(final Integer max_Lengh) {
return new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent e) {
TextField txt_TextField = (TextField) e.getSource();
if (txt_TextField.getText().length() >= max_Lengh) {
e.consume();
}
if(e.getCharacter().matches("[0-9.]")){
if(txt_TextField.getText().contains(".") && e.getCharacter().matches("[.]")){
e.consume();
}else if(txt_TextField.getText().length() == 0 && e.getCharacter().matches("[.]")){
e.consume();
}
}else{
e.consume();
}
}
};
}
/*****************************************************************************************/
/* Letters Validation Limit the characters to maxLengh AND to ONLY Letters *************************************/
public EventHandler<KeyEvent> letter_Validation(final Integer max_Lengh) {
return new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent e) {
TextField txt_TextField = (TextField) e.getSource();
if (txt_TextField.getText().length() >= max_Lengh) {
e.consume();
}
if(e.getCharacter().matches("[A-Za-z]")){
}else{
e.consume();
}
}
};
}
/*****************************************************************************************/
@FXML public void processKeyEvent(KeyEvent ev) {
String c = ev.getCharacter();
if("1234567890".contains(c)) {}
else {
ev.consume();
}
}
package limitedtextfield;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class CustomControlExample extends Application {
@Override
public void start(Stage stage) throws Exception {
LimitedTextField customControl = new LimitedTextField();
customControl.setText("Hello!");
stage.setScene(new Scene(customControl));
stage.setTitle("Custom Control");
stage.setWidth(300);
stage.setHeight(200);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<HBox>
<limitedtextfield.LimitedTextField text="Hello World!"/>
</HBox>
package limitedtextfield;
import javafx.scene.control.TextField;
public class LimitedTextField extends TextField
{
private String characters;
private int max;
private boolean capital = false;
private boolean space = true;
static public final String CharactersNumbers = "[qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890èéòàùì ]";
static public final String Characters = "[qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNMèéòàùì ]";
static public final String Numbers = "[1234567890 ]";
static public final String NumbersPoint = "[1234567890. ]";
public LimitedTextField(String l){
super();
characters = l;
max=0;
}
public LimitedTextField(){
super();
characters = "";
max=0;
}
public LimitedTextField(String l, int max){
super();
characters = l;
this.max=max;
//System.out.println("Costruttore");
}
public LimitedTextField(int max){
super();
characters = "";
this.max=max;
}
@Override
public void replaceText(int start, int end, String text)
{
if(!characters.equals("")){
if (validateCh(text))
{
text = check(text);
super.replaceText(start, end, text);
if(max>0)
verifyLengh();
}
}else{
text = check(text);
super.replaceText(start, end, text);
if(max>0)
verifyLengh();
}
}
@Override
public void replaceSelection(String text)
{
if(!characters.equals("")){
if (validateCh(text))
{
text = check(text);
super.replaceSelection(text);
if(max>0)
verifyLengh();
}
}else{
text = check(text);
super.replaceSelection(text);
if(max>0)
verifyLengh();
}
}
private boolean validateCh(String text)
{
/*
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |
*/
return ("".equals(text) || text.matches(characters));
}
private void verifyLengh() {
if (getText().length() > max) {
setText(getText().substring(0, max));//use this line if you want to delete the newer characters inserted
//setText(getText().substring(getText().length()-max, getText().length()));//use this line if you want to delete the older characters inserted
positionCaret(max);//set the cursor position
}
}
private String check(String text){
if(capital)
text = text.toUpperCase();
if(!space)
text = text.replace(" ", "");
return text;
}
public void setLimitCharachters(String s){
this.characters = s;
}
public String getLimitCharachters(){
return characters;
}
public void setMaxLenght(int s){
this.max= s;
}
public int getMaxLenght(){
return max;
}
public boolean getCapital(){
return this.capital;
}
public void setCapital(boolean t){
this.capital = t;
}
public boolean getSpace(){
return this.space;
}
public void setSpace(boolean t){
this.space = t;
}
}
...
<?import limitedtextfield.*?>
...
<HBox alignment="CENTER_LEFT" spacing="5.0">
<children>
<Label text="Name:" />
<LimitedTextField fx:id="A_Name_S" />
</children>
<FlowPane.margin>
<Insets right="5.0" />
</FlowPane.margin>
</HBox>
...
...
import limitedtextfield.LimitedTextField;
@FXML
private LimitedTextField A_Name_S;
...
@Override
public void initialize(URL url, ResourceBundle rb) {
A_Name_S.setSpace(false);
A_Name_S.setCapital(true);
A_Name_S.setMaxLenght(20);
A_Name_S.setLimitCharachters(LimitedTextField.Characters);
}
@FXML
void verifnum(KeyEvent event) {
txt.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue,
String newValue) {
if (!newValue.matches("\\d*")) {
txt.setText(newValue.replaceAll("[^\\d]", ""));
}
}
});
}