Control keyboard input into javafx TextField

后端 未结 6 1719
清酒与你
清酒与你 2020-12-31 17:44

I want to control the input into a Javafx TextField so that I can allow only Numeric input, and so that if the max characters are exceeded, then no change will be made to th

相关标签:
6条回答
  • 2020-12-31 17:51

    Try this solution add this function in your controller , you must add it on the keyPressed Action of your text field.

    @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]", ""));
                }
            }
        });
    }
    
    0 讨论(0)
  • 2020-12-31 17:58

    the best way is :

        @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();
                }
            }
        };
    }    
    /*****************************************************************************************/
    

    Best of luck.

    0 讨论(0)
  • 2020-12-31 17:58

    Final solution. Disallows alphabetic and special characters and enforces character limit.

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-31 17:58

    I simply set the 'On Key Typed' event to run this small procedure:

        @FXML public void processKeyEvent(KeyEvent ev) {
        String c = ev.getCharacter();
        if("1234567890".contains(c)) {}
        else {
            ev.consume();
        }
    }
    

    It works like a champ!

    0 讨论(0)
  • 2020-12-31 17:59

    I have created a customized Textfield that can be added to Java Builder FX (using 'import JAR/FXML file...').

    With this TextField can be set

    1. the characters or numbers allowed
    2. if there is or not the space character
    3. if the input is only CAPITAL (the shown output is in capital)
    4. and the lenght.

    Of course can be improoved, but it's quite usefull. Hope that this will help someone :)

    FX Project LimitedTextField With this project can be created the 'LimitedTextField.jar' file to import in your application or in java builder FX.

    CustomControlExample.java

    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);
        }
    }
    

    custom_control.fxml

    <?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>
    

    LimitedTextField.java

    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;
        }
    }
    

    Example of use:

    MyFxmlApplication.fxml

    ...
    <?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>
    ...
    

    MyFxmlApplicationController.fxml

    ...
    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);
    }
    

    bye

    0 讨论(0)
  • 2020-12-31 18:09

    Here is my aproach, two event filters, could be one, in my case i used them in diferent situations, thats why there are two.

    Here is the maxValueFilter (in spanglish xD), this one is a class:

    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();
                }
    
            }
        }
    

    And the other event filter (filters the chars), this one is a method:

    public static EventHandler<KeyEvent> numFilter() {
    
            EventHandler<KeyEvent> aux = new EventHandler<KeyEvent>() {
                public void handle(KeyEvent keyEvent) {
                    if (!"0123456789".contains(keyEvent.getCharacter())) {
                        keyEvent.consume();
    
                    }
                }
            };
            return aux;
        }
    

    the use in your case would be:

    field.addEventFilter(KeyEvent.KEY_TYPED,
                    numFilter());
    field.addEventFilter(KeyEvent.KEY_TYPED, new FiltroValorMaximo(
                    99));
    
    0 讨论(0)
提交回复
热议问题