0

I'm trying to make a function that hides a JButton when pressing H. I'm using KeyListener to detect if the "H" button has been pressed. Currently I'm trying to detect any button press. The problem is that nothing is detected and nothing happens. Code Below is the JPanel. Ignore the methods since they do not affect the key detection.

    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  
}
}    
F.johansson
  • 83
  • 14
  • The problem is that you're setting `super` to be in focus. For the `KeyListener` to operate properly, the `Component` to which the `KeyListener` is applied must be in focus – CraigR8806 May 10 '17 at 18:00
  • 1
    Variable names should NOT start with an upper case character. Follow Java conventions. – camickr May 10 '17 at 18:45
  • In my experience, KeyBindings work better. Checkout this link http://stackoverflow.com/questions/15290035/key-bindings-vs-key-listeners-in-java?rq=1 – a_m May 10 '17 at 18:49

3 Answers3

3

There are a number of issues.

First, you're adding the KeyListener to the JFrame, the problem with that is, a JFrame is made of a number of other components...

JRootPane

The next problem is, the KeyListener will only respond to key events if:

  1. The component is focusable AND
  2. The component has keyboard focus

So, when you add other components to the UI, I'm assuming that Return and HideHint are actually JButtons, they can, and often do, steal focus rendering your KeyListener useless.

As is almost the case with KeyListener, the answer is, don't use it. No seriously. If you want more control over when a key event is triggered, then you should use the Key Bindings API which provides not only a more flexible and re-usable API, but provides you with control over how to configure the at what focus level a key event would be triggered

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

In order for the KeyListener to fire a KeyEvent, you have to be inside the Listened Object (it has to be in focus). If you put other Objects like Buttons or TextFields upon your Frame you block the keyListener on these places.

Musti
  • 139
  • 1
  • 9
0

Try setting your KeyListener to super like so:

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

As stated in the comments, the problem you're having is that you're setting your KeyListener to a JFrame that is being passed into your constructor. Then you are setting the object that is being constructed to be in focus by calling super.requestFocusInWindow()

To allow the KeyListener to properly do it's job the Component to which the KeyListener is attached, must be in focus.

CraigR8806
  • 1,584
  • 13
  • 21