JavaFX中的KeyEvent(KeyPressed)无法修复

时间:2015-01-17 19:48:48

标签: netbeans javafx

我正在尝试构建一个JavaFX FXML应用程序,我有一个TextField,我想按下Enter Key并且光标位于TextField中,该键将执行某些操作...我将此代码转移到它有一个错误我无法解决它:

       @FXML
      private void onKeyTyped (ActionEvent ee) { 
     text1.setOnKeyPressed(new EventHandler<KeyEvent>() {
         public void keyt (KeyEvent evt) throws IOException{
          //do something
       }
        });
       }

所以请帮助我,谢谢:)

2 个答案:

答案 0 :(得分:1)

您可以通过在文本字段的fxml文件的场景构建器中设置fx id来实现此目的。这应该摆脱&#34; private void onKeyTyped(ActionEvent ee){&#34;然后在控件类的initialize方法中,例如MainControl,你需要添加用事件处理程序按下的键上的set 以下是一个示例:

package application;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;

public class MainControl implements Initializable {
@FXML
TextField text1;
public void initialize(URL arg0, ResourceBundle arg1) {// Initializes
                                                        // everything
    text1.setOnKeyPressed(new EventHandler<KeyEvent>() {// Keyboard                                             // commands
        public void handle(KeyEvent ke) {
            if (ke.getCode().toString().equalsIgnoreCase("ENTER")) {
            //do something

    }   
    }
    });



}
}

我希望这有助于

答案 1 :(得分:1)

TextFiledEvent.class

public class TextFiledEvent extends Application {

    @Override
    public void start(Stage primaryStage) {
        TerminalTextField btn = new TerminalTextField();
        VBox root = new VBox();
        root.getChildren().add(btn);

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

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

}

TerminalTextField.class

class TerminalTextField extends TextField {

    ArrayList<String> arrayList = new ArrayList<>();
    int sizeOfList = 10;
    int keyPoint;

    public TerminalTextField() {
        setField();
    }

    public TerminalTextField(String text) {
        super(text);
        setField();
    }

    private void setField() {
        setOnKeyReleased(new EventHandler<KeyEvent>() {

            @Override
            public void handle(KeyEvent event) {
                if (event.getCode().isLetterKey()) {
                    setText(getText().toString().toUpperCase());
                    positionCaret(getLength());
                }
            }
        });
    }

}