如果我问的问题太大,请原谅我,我尝试学习编码,我想我缺少关于KeyListiner的大量细节。我正在尝试制作一个简单的程序,“滚动骰子”并在用户按下键时显示数字1到6的图片。我的程序似乎未响应任何用户输入。

我究竟做错了什么?

谢谢您的帮助,我只是在尝试学习,以便您提出任何建议。

public class Dice   {

 public static void  main (String arg[]) {
     new DD();
 }
}

class DD extends JPanel {
DD(){

    JFrame frame = new JFrame();
    ImageIcon icon = new ImageIcon("dice.jpg");
    JLabel label = new JLabel(icon);
    frame.add(label);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    addKeyListener(new Roll());
    }
}

class Roll extends JFrame implements KeyListener {

public void keyPressed(KeyEvent event){}
public void keyReleased(KeyEvent event){}
public void keyTyped(KeyEvent event){
    int d = event.getKeyCode();
    if(d == KeyEvent.VK_UP){
        int roll = (int) (Math.random()*6) + 1;
        System.out.println(roll);
  }
 }
}

最佳答案

让我们仔细看看您的DD类...

class DD extends JPanel {

    DD() {

        JFrame frame = new JFrame();
        ImageIcon icon = new ImageIcon("dice.jpg");
        JLabel label = new JLabel(icon);
        frame.add(label);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        addKeyListener(new Roll());
    }
}



您在JFrame的构造函数中创建JPanel的实例,这是一个有问题的行为...
您创建一个JLabel并将其添加到JFrame
您显示JFrame
您将KeyListener添加到DD JPanel


但是请稍等,DD从未附加到任何可见组件,怎么可能接收到关键事件呢?

KeyListener仅在其注册的组件可聚焦且具有焦点时才起作用,但是如果它从未显示在屏幕上,则它永远不会具有焦点!

首先,我将避免使用KeyListener,它具有与焦点相关的问题,而应使用Key Bindings API

例如...

import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Dice {

    public static void main(String[] args) {
        new Dice();
    }

    public Dice() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new DD());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    class DD extends JPanel {

        DD() {
            setLayout(new GridBagLayout());
            JLabel label = new JLabel(" - ");
            add(label);

            addKeyBindingFor(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "Action.roll", new DiceRollAction(label));
        }

        protected void addKeyBindingFor(KeyStroke keyStroke, String name, Action action) {
            InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap actionMap = getActionMap();

            inputMap.put(keyStroke, name);
            actionMap.put(name, action);
        }

        public class DiceRollAction extends AbstractAction {

            private JLabel label;

            public DiceRollAction(JLabel label) {
                this.label = label;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                int roll = (int) (Math.random() * 6) + 1;
                label.setText(Integer.toString(roll));
            }
        }

    }

}

关于java - Java KeyListener没有响应,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36852230/

10-12 01:31