如何让 EvenHandler 在 JavaFX 中正常工作?

How to make EvenHandler work properly in JavaFX?

我重新安排了我的问题,这样会更容易。

此代码应生成 Window,我需要按下键盘时的控制台输出。 Window 出现,但我的 EventHandlers 不工作。

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Main  {

    public static void main(String[] args) {
        JFrame frame = new JFrame("JavaFX in Swing");
        frame.setLayout(new BorderLayout());

        Charts charts = new Charts();

        frame.setSize(1024, 720); //Size of dispalayed window
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static class Charts extends JPanel implements KeyListener{

        public Charts(){
            addKeyListener(this);
        }

        @Override
        public void keyTyped(java.awt.event.KeyEvent key) {
            if(key.getKeyCode() == KeyEvent.VK_DOWN){
                System.out.println("DOWN");
            }
        }

        @Override
        public void keyPressed(java.awt.event.KeyEvent key) {
            if(key.getKeyCode() == KeyEvent.VK_DOWN){
                System.out.println("DOWN");
            }
        }

        @Override
        public void keyReleased(java.awt.event.KeyEvent key) {
            if(key.getKeyCode() == KeyEvent.VK_DOWN){
                System.out.println("DOWN");
            }
        }
    }
}

这个 EventHandler 不工作我做错了什么?

public static void main(String[] args) {
    // there's no JavaFX in this example
    JFrame frame = new JFrame("JavaFX in Swing");
    frame.setLayout(new BorderLayout());

    Charts charts = new Charts();

    // add charts panel to frame to allow swing manage it in event processing
    frame.setContentPane(charts);

    frame.setSize(1024, 720); //Size of dispalayed window
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static class Charts extends JPanel {

    public Charts(){
        // Keylistener wont't work if there is no focused component (ie JTextField)
        // JPanel is not focusable component
        // So use registerKeyboardAction to handle events
        registerKeyboardAction(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("DOWN press");
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), WHEN_IN_FOCUSED_WINDOW);

        registerKeyboardAction(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("DOWN release");
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), WHEN_IN_FOCUSED_WINDOW);
    }

}