KeyListener未检测到按键

时间:2017-05-10 17:55:58

标签: java swing keylistener

我正在尝试创建一个在按下H时隐藏JButton的函数。我正在使用KeyListener来检测是否已按下“H”按钮。目前我正试图检测任何按钮按下。问题是没有检测到任何东西,也没有任何反应。代码如下是JPanel。忽略这些方法,因为它们不会影响密钥检测。

    public GamePanel(CardLayout cl, JPanel MainPanel, JFrame frame){
    this.cl = cl;
    this.MainPanel = MainPanel;
    DropColor = DropColorRead();
    this.frame = frame;
    this.frame.addKeyListener(new KeyListener(){

        @Override
        public void keyPressed(KeyEvent arg0) {
            System.out.println("asdhuasdiu");

        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void keyTyped(KeyEvent arg0) {
            // TODO Auto-generated method stub  
        }
    });

    super.setFocusable(true);
    super.requestFocusInWindow();

    // Setting the required space for the array "Rain".
    Rain = new JPanel[amount];

    // Allowing random placement of Object on JPanel.
    super.setLayout(null);
    super.setBackground(BackgroundChange());

    Return.addActionListener(this);
    Return.setFont(new Font("Sans-serif", Font.BOLD, 18));
    Return.setBackground(Color.white);
    super.add(Return);

    HideHint.setFont(new Font("Sans-serif", Font.BOLD, 18));
    HideHint.setBackground(Color.white);

    super.add(HideHint);

    Return.setLocation(50, (frame.getHeight() - 75));
    Return.setSize(200, 30);

    HideHint.setLocation((frame.getWidth() / 2 - 150), (frame.getHeight() - 100));
    HideHint.setSize(300, 30);

    tm.start();
}

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == Return){
        cl.show(MainPanel, "1");
        tm.stop();
        System.out.println("Rain Paused");
    }

    //First time rendering of the raindrops.
    Generate();

    for(int i = 0; i < amount; i++){
        y[i] += v[i];

        //Changing the velocity depending on location and gravity.
        Velocity(i);

        //Brightening the dropcolor the further down.
        ColorChange(i);

        //When a raindrop reaches the bottom of the screen
        Regenerate(i);

        Rain[i].setBackground(NewDropColor[i]);
        Rain[i].setLocation(x[i], y[i]);
    }
    flag = false;
}

public void Generate(){
    if(flag){
        for(int i = 0; i < amount; i++){
            Rain[i] = new JPanel();

            NewDropColor[i] = DropColor;
            Rain[i].setBackground(NewDropColor[i]);

            x[i] = (int) (Math.random() * frame.getWidth());       
            y[i] = (int) (Math.random() * -frame.getHeight());
            w[i] = (int) (Math.random() * 4);
            h[i] = (int) (Math.random() * 13);
            v[i] = (int) (Math.random() * 6);
            g[i] = (int) (Math.random() * 150);

            if(h[i] < 7) h[i] += 6;

            if(w[i] < 3) w[i] += 3;

            if(w[i] == 5) w[i] = 4;

            if(v[i] < 3) v[i] += 3;

            if(g[i] < 75) g[i] += 90;

            super.add(Rain[i]);
            Rain[i].setLocation(x[i], y[i]);
            Rain[i].setSize(w[i], h[i]);
        }
        System.out.println("Rain Running");
    }
}

public void ColorChange(int i){
    if(y[i] > -frame.getHeight()/10){
        if(y[i] % 10 == 0 || y[i] % 9 == 0){
            if(NewDropColor[i].getRed() < (256 - ColorIncrease) && NewDropColor[i].getGreen() < (256 - ColorIncrease) && NewDropColor[i].getBlue() < (256 - ColorIncrease)){
                NewDropColor[i] = new Color(NewDropColor[i].getRed() + ColorIncrease, NewDropColor[i].getGreen() + ColorIncrease, NewDropColor[i].getBlue() + ColorIncrease);
            }
        }
    }
}

public void Regenerate(int i){
    if(y[i] >= frame.getHeight()){
        x[i] = (int) (Math.random() * frame.getWidth()); 
        v[i] = (int) (Math.random() * 6);

        NewDropColor[i] = DropColor;

        if(v[i] < 3) v[i] += 3;

        y[i] = -10;
    }
}

public void Velocity(int i){
    if(y[i] % g[i] == 0 || y[i] % g[i] == 1 || y[i] % g[i] == 2){
        v[i] += 1;
    }
}

public static int SpeedRead(){
    int Speed = 0;
    try{
        String Ignore;
        BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream("Settings.txt")));
        Ignore = file.readLine();
        Ignore = file.readLine();

        Speed = Integer.parseInt(file.readLine());

        file.close();
    }
    catch(IOException e){
        System.out.println("Something went wrong loading Settings...");
    }

    return Speed;
}

public static Color DropColorRead(){
    Color DropColor = null;

    try{
        int Red, Green, Blue;
        String Color, Ignore;
        BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream("Settings.txt")));
        Ignore = file.readLine();
        Color = file.readLine();

        Red = Integer.parseInt(Color.substring(0, 3));
        Green = Integer.parseInt(Color.substring(4, 7));
        Blue = Integer.parseInt(Color.substring(8, 11));

        DropColor = new Color(Red, Green, Blue);
        file.close();
    }
    catch(IOException e){
        System.out.println("Something went wrong loading Settings...");
    }

    return DropColor;
}

public static Color BackgroundChange(){
    Color BackColor = null;

    try{
        int Red, Green, Blue;
        String Color;
        BufferedReader file = new BufferedReader(new InputStreamReader(new FileInputStream("Settings.txt")));
        Color = file.readLine();

        Red = Integer.parseInt(Color.substring(0, 3));
        Green = Integer.parseInt(Color.substring(4, 7));
        Blue = Integer.parseInt(Color.substring(8, 11));

        BackColor = new Color(Red, Green, Blue);
        file.close();
    }
    catch(IOException e){
        System.out.println("Something went wrong loading Settings...");
    }

    return BackColor;
}

@Override
public void keyPressed(KeyEvent arg0) {
    System.out.println("asdhuasdiu");
}

@Override
public void keyReleased(KeyEvent arg0) {
    // TODO Auto-generated method stub
}

@Override
public void keyTyped(KeyEvent arg0) {
    // TODO Auto-generated method stub  
}
}    

3 个答案:

答案 0 :(得分:2)

有很多问题。

首先,您要将KeyListener添加到JFrame,问题是,JFrame是由多个其他组件构成的......

JRootPane

下一个问题是,KeyListener只会在以下情况下响应关键事件:

  1. 该组件是可聚焦的
  2. 该组件具有键盘焦点
  3. 因此,当您向UI添加其他组件时,我假设ReturnHideHint实际上是JButton,他们可以并且经常会窃取焦点使你的KeyListener无用。

    KeyListener几乎一样,答案是,不要使用它。不认真。如果您想要更好地控制触发键事件的时间,那么您应该使用Key Bindings API,它不仅提供更灵活且可重复使用的API,还可以控制如何配置焦点级别将触发关键事件

答案 1 :(得分:0)

为了让KeyListener触发KeyEvent,你必须在Listened Object中(它必须是焦点)。如果在框架上放置Buttons或TextFields等其他对象,则会在这些位置阻止keyListener。

答案 2 :(得分:0)

尝试将KeyListener设置为super,如下所示:

super.addKeyListener(new KeyListener(){
    //code for listener
});

正如评论中所述,您遇到的问题是您正在将KeyListener设置为传递给构造函数的JFrame。然后,您通过调用super.requestFocusInWindow()

将正在构造的对象设置为焦点

要让KeyListener正确完成工作,Component所附加的KeyListener必须成为焦点。