2017-09-25 6 views
0

글쎄, 저는 Java FX를 공부하고 있습니다 만, 이번엔 NetBeans에서 FXML을 사용하고 있습니다. 그런 다음 TextField에서 허용하는 키를 제한하려고합니다. 그냥 숫자 또는 그냥 문자처럼.필터 키보드 TextField Java FXML

This 나는 새로운 클래스를 만든 다음 해당 코드를 링크에 올바른 것으로 두었습니다. TextField를 확장하지만 코드를 실행하면 예외가 발생합니다. 왜냐하면 SceneBuilder는 내 수업은 없어.

import java.util.function.UnaryOperator; 
import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.control.TextField; 
import javafx.scene.control.TextFormatter; 
import javafx.scene.control.TextFormatter.Change; 
import javafx.scene.layout.VBox; 
import javafx.stage.Stage; 

/** 
* 
* @author Alejandro 
*/ 
public class JavaFXApplication2 extends Application { 

@Override 
public void start(Stage primaryStage) { 

    TextField textField = new TextField(); 
    TextFormatter<String> textFormatter = getTextFormatter(); 
    textField.setTextFormatter(textFormatter); 

    VBox root = new VBox(); 

    root.getChildren().add(textField); 

    Scene scene = new Scene(root, 300, 250); 

    primaryStage.setTitle("TextFormat"); 
    primaryStage.setScene(scene); 
    primaryStage.show(); 
} 

private TextFormatter<String> getTextFormatter() { 
    UnaryOperator<Change> filter = getFilter(); 
    TextFormatter<String> textFormatter = new TextFormatter<>(filter); 
    return textFormatter; 
} 

private UnaryOperator<Change> getFilter() { 
    return change -> { 
     String text = change.getText(); 

     if (!change.isContentChange()) { 
      return change; 
     } 

     if (text.matches("[a-z]*") || text.isEmpty()) { 
      return change; 
     } 

     return null; 
    }; 
} 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
    launch(args); 
} 

} 

그 코드는 위의 자바 FX 애플리케이션에서 잘 작동하지만 내가 자바 FXML에 사용할 하나가 필요 올리기 유사한 코드보다 한 사람 :

업데이트 난 자바 FX에 대한 유사한 코드를 발견 그것은 컴파일, 아니 예외를 trows,하지만 작동하지 않습니다, 또는 그것을 구현하는 방법을 모르겠습니다.

+1

. 이런 종류의 기능을 위해서'TextFormatter'를 사용해야합니다. 예를 들어 https://stackoverflow.com/questions/40472668/numeric-textfield-for-integers-in-javafx-8-with-textformatter-and-or-unaryoperat –

답변

0

당신이이 같은 textformatter을 사용할 수 있습니다 단지 ALPHA/NUMERIC에 텍스트를 제한하려면 :

public class MaxLengthTextFormatter extends TextFormatter<String> { 
    private int maxLength; 

public MaxLengthTextFormatter(int maxLength) { 
    super(new UnaryOperator<TextFormatter.Change>() { 
     @Override 
     public TextFormatter.Change apply(TextFormatter.Change change) { 
      //If the user is deleting the text (i.e. full selection, ignore max to allow the 
      //change to happen) 
      if(change.isDeleted()) { 
       //if the user is pasting in, then the change could be longer 
       //ensure it stops at max length of the field 
       if(change.getControlNewText().length() > maxLength){ 
        change.setText(change.getText().substring(0, maxLength)); 
       } 

      }else if (change.getControlText().length() + change.getText().length() >= maxLength) { 
       int maxPos = maxLength - change.getControlText().length(); 
       change.setText(change.getText().substring(0, maxPos)); 
      } 
      return change; 
     } 
    }); 
    this.maxLength = maxLength; 
} 

public int getMaxLength() 
{ 
    return maxLength; 
} 

} 단지는 숫자와 문자를 허용하는 것보다 포매터를 생성

public class AlphaNumericTextFormatter extends TextFormatter<String> { 

    /** The Constant ALPHA_NUMERIC_ONLY. */ 
    //private static final String ALPHA_NUMERIC_ONLY = "^[a-zA-Z0-9]*$"; 
    /** MAKE NUMERIC ONLY **/ 
    private static final String DIGITS_ONLY = "^[0-9]*$"; 

    /** 
    * Instantiates a new alpha numeric text formatter. 
    */ 
    public AlphaNumericTextFormatter() { 
     super(applyFilter(null)); 
    } 

    /** 
    * Instantiates a new alpha numeric text formatter. 
    * 
    * @param maxLength 
    *   the max length 
    */ 
    public AlphaNumericTextFormatter(int maxLength) { 
     super(applyFilter(new MaxLengthTextFormatter(maxLength).getFilter())); 
    } 

    /** 
    * Apply filter. 
    * 
    * @param filter 
    *   the filter 
    * @return the unary operator 
    */ 
    private static UnaryOperator<Change> applyFilter(UnaryOperator<Change> filter) { 
     return change -> { 
      if (change.getControlNewText() != null && change.getControlNewText().matches(DIGITS_ONLY)) { 
       if (filter != null) { 
        filter.apply(change); 
       } 
       return change; 
      } 
      return null; 
     }; 
    } 

} 

- 패턴을 자신의 필요에 맞게 조정할 수 있습니다. 당신은이처럼 텍스트 필드에 첨부

.... 링크가 꽤 오래된 것을

@FXML 
private TextField myTextField; 


@FXML 
private void initialize() { 
    //Create a alpha field which max length of 4 
    myTextField.setTextFormatter(new AlphaNumericTextFormatter(4)); 
} 
+0

응답 해 주셔서 감사합니다. 코드는 작동하지만 충분히 설명하지 못했습니다. , KeyEvent를 포착하고 TextField에 표시하도록 허용하지 않습니다. – Palomino9r

+0

내가 무엇을 요구하는지 잘 모르겠다. 모든 키 입력을 제한 하시겠습니까? 그렇다면 텍스트 필드를 편집 할 수 없도록 설정하십시오. 그게 당신이 요구하는 것입니까? –

+0

모든 키 입력이 아니라 일부 키만 TextField에서 숫자 또는 A-Z로 제한합니다. 입력란에 이름을 입력 할 때처럼 시스템에서 문자를 입력 할 수 있고 숫자가 아닌 특수 문자는 입력 할 수있는 것처럼 유효성 검사 프로세스를위한 것입니다. – Palomino9r