简体   繁体   中英

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:

Error 1:

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

Error 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. You're using KeyEvent.getKeyCode() from javafx.scene.input while the constants KeyEvent.VK_* are for java.awt.event

I get the ENTER-Key like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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