简体   繁体   English

JavaFX-获取EnterKey的KeyCode以执行带有文本字段的事件以转到输入的网址

[英]JavaFX - Getting KeyCode for Enter Key to execute Event with Text Field to go to entered web address

I have Tried to get the enter key keycode when the enter key is pressed to go to the entered web address. 我试图在按下回车键转到输入的网址时获取回车键密码。 when I try to do that, it gives me an error. 当我尝试这样做时,它给我一个错误。

How can I fix it so it will work? 我该如何修复它才能起作用?

package fxmlstuffs;

import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.scene.web.WebEngine;
import javafx.scene.input.KeyEvent;

public class FXMLDocumentController implements Initializable {

    WebEngine web = new WebEngine();

    @FXML
    private TextField url;


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        assert url != null : "fx:id =\"url\" was not injected: check your FXML file";

        url.setOnKeyPressed(new EventHandler<KeyEvent>(){
            @Override
            public void handle(KeyEvent ke){
                int key = ke.getKeyCode();
                if(key == KeyEvent.VK_ENTER){
                    web.load(url.getText());
                }
            }
        });
    }
}

The Specific errors straight from Netbeans: 来自Netbeans的特定错误:

Error 1: 错误1:

error: cannot find symbol
                int key = ke.getKeyCode();
  symbol:   method getKeyCode()
  location: variable ke of type KeyEvent

Error 2: 错误2:

error: cannot find symbol
                if(key == KeyEvent.VK_ENTER){
  symbol:   variable VK_ENTER
  location: class KeyEvent

To elaborate on blaster's answer, it is because you're mixing up the JavaFX and AWT KeyEvent classes. 要详细说明blaster的答案,这是因为您要混合使用JavaFX和AWT KeyEvent类。 You're using KeyEvent.getKeyCode() from javafx.scene.input while the constants KeyEvent.VK_* are for java.awt.event 您正在使用javafx.scene.input KeyEvent.getKeyCode() ,而常数KeyEvent.VK_*则用于java.awt.event

I get the ENTER-Key like this: 我得到这样的ENTER键:

    public class FXMLDocumentController implements Initializable {

        WebEngine web = new WebEngine();

        @FXML
        private TextField url;


        @Override
        public void initialize(URL location, ResourceBundle resources) {
            assert url != null : "fx:id =\"url\" was not injected: check your FXML file";

            url.setOnKeyPressed(new EventHandler<KeyEvent>(){
                @Override
                public void handle(KeyEvent ke){
                     KeyCode key = ke.getCode();
                    if(key == KeyCode.ENTER){
                        web.load(url.getText());
                    }
                }
            });
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM