0

I am trying to create a game but my key bindings are not working and I am not sure why. the code included will run if given pictures and graphics data for image icons. When running the game the key bind gets input into the key map but it cannot be used for some odd reason. If anyone has any clue as to why it might be doing this that would be much appreciated.

graphics/ui:

     package Ballerz;
     import java.util.*;
     import java.awt.*;
     import java.awt.event.ActionEvent;
     import java.awt.event.ActionListener;
     import java.awt.event.KeyAdapter;
     import java.awt.event.KeyEvent;
     import java.awt.event.KeyListener;

import javax.swing.*;
import java.io.*;
public class GraphicsPn extends Game{



    public GraphicsPn() throws IOException{
    
    frame.setUndecorated(true);
    frame.setName("Ballerz");
    frame.setIconImage(window.getImage());
    frame.setContentPane(startMenu);
    frame.validate();
            
    startMenu.setLayout(bord);
    startMenu.setPreferredSize(new Dimension(1366, 768));
    //top menu design
    startMenu.add(topMenu);
        topMenu.setPreferredSize(new Dimension(1366, 40));
        topMenu.setBackground(Color.BLACK);
        topMenu.setForeground(Color.WHITE);
        topMenu.setAlignmentX(topMenu.RIGHT_ALIGNMENT);
        topMenu.setLayout(bord);
    setScene.add(topMenu);
        topMenu.setPreferredSize(new Dimension(1366, 40));
        topMenu.setBackground(Color.BLACK);
        topMenu.setForeground(Color.WHITE);
        topMenu.setAlignmentX(topMenu.RIGHT_ALIGNMENT);
        topMenu.setLayout(bord);
        
    topMenu.add(X, bord.EAST);
        X.setLabel("X");
        X.setFont(new Font(title.getName(), Font.ITALIC, 20));
        X.setBackground(Color.BLACK);
        X.setForeground(Color.WHITE);
        X.setSize(new Dimension(50,40));
        X.setFocusPainted(false);
        X.setBorderPainted(false);
        X.doLayout();
                
    startMenu.add(menu, bord.EAST);
    
    ballerz.setIcon(gif);
    ballerz.setPreferredSize(new Dimension(768,768));
    startMenu.add(ballerz, bord.WEST);
        
    //menu Design
    menu.setPreferredSize(new Dimension(598, 700));
    menu.setBackground((Color.BLACK));
    menu.setLayout(grid);
    menu.setAlignmentY(menu.BOTTOM_ALIGNMENT);
    grid.setVgap(30);
    
    menu.add(title);
        title.setForeground(Color.WHITE);
        title.setPreferredSize(new Dimension(598, 150));
        title.setFont(new Font(title.getName(), Font.ITALIC, 70));
    
    menu.add(start);
        start.setBackground(Color.BLACK);
        start.setForeground(Color.WHITE);
        start.setLabel("New Game");
        start.setFocusPainted(false);
        start.setFont(new Font(title.getName(), Font.ITALIC, 25));
        start.setBorderPainted(false);
        start.setSize(598,50);
        start.doLayout();
    menu.add(settings);
        settings.setBackground(Color.BLACK);
        settings.setForeground(Color.WHITE);
        settings.setLabel("Settings");
        settings.setFocusPainted(false);
        settings.setFont(new Font(title.getName(), Font.ITALIC, 25));
        settings.setBorderPainted(false);
        settings.setSize(598,50);
        settings.doLayout();
        
    menu.add(help);
        help.setBackground(Color.BLACK);
        help.setForeground(Color.WHITE);
        help.setLabel("How to Play");
        help.setFocusPainted(false);
        help.setFont(new Font(title.getName(), Font.ITALIC, 25));
        help.setBorderPainted(false);
        help.setSize(598,50);
        help.doLayout();
    menu.add(exit);
        exit.setBackground(Color.BLACK);
        exit.setForeground(Color.WHITE);
        exit.setLabel("Exit");
        exit.setFocusPainted(false);
        exit.setFont(new Font(title.getName(), Font.ITALIC, 25));
        exit.setBorderPainted(false);
        exit.setSize(598,50);
        exit.doLayout();
        
        
        
        
    menu.add(source);
        source.setFont(new Font(title.getName(), Font.ITALIC, 12));
    //help design
        helpScene.setPreferredSize(new Dimension(1366, 768));
        helpScene.setBackground(Color.BLACK);
        helpScene.add(topMenu);
        
    ActionListener clic = new ActionListener(){ public void actionPerformed(ActionEvent e) {
        if(e.getSource().equals(help)){
            frame.setContentPane(helpScene);
            frame.revalidate();
            frame.repaint();
            helpScene.requestFocus();
            helpScene.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent e) {
                    helpScene.requestFocus();
                    System.out.println("pressed " + e.getKeyCode());
                    if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                        frame.setContentPane(startMenu);
                        frame.repaint();
                    }
        }});
            frame.repaint();
            }
        if(e.getSource().equals(start)){
            frame.setContentPane(game);
            frame.invalidate();
            frame.revalidate();
            game.requestFocus();
            frame.repaint();
            
        }
        if(e.getSource().equals(settings)){
            frame.setContentPane(setScene);
            setScene.setBackground(Color.BLACK);
            setScene.requestFocus();
            setScene.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent e) {
                    setScene.requestFocus();
                    System.out.println("pressed " + e.getKeyCode());
                    if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
                        frame.setContentPane(startMenu);
                        frame.repaint();
                    }
                    
        }});
            frame.repaint();
            }
            
        if(e.getSource().equals(X)) {
            frame.setContentPane(startMenu);
            frame.revalidate();
            frame.repaint();
        }
        if(e.getSource().equals(exit)){
            System.exit(0);
        }
    }};
    exit.addActionListener(clic);
    X.addActionListener(clic);
    start.addActionListener(clic);
    help.addActionListener(clic);
    settings.addActionListener(clic);
    
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frame.setVisible(true);
    frame.setBackground(Color.black);
    startMenu.setVisible(true);
    
    
    
}
}

game section:

    package Ballerz;

import java.util.*;
import java.awt.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.*;
import java.lang.*;



public class Game extends JPanel {

public int x;
public int y;
public int x2;
public int y2;
public double dis1;
public double dis2;

public JLayeredPane game = new JLayeredPane();
public JPanel players = new JPanel();
JFrame frame = new JFrame();
JLabel ballerz = new JLabel();

public JPanel startMenu = new JPanel();
JPanel helpScene = new JPanel();
JPanel setScene = new JPanel();

JLabel title = new JLabel("Ballerz", JLabel.CENTER);
JLabel source = new JLabel("Gif by ShotoPop: https://media.giphy.com/media/3DrHrnC0JMotPiopno/giphy.gif", JLabel.CENTER);

JPanel menu = new JPanel();
JButton help = new JButton();
JButton start = new JButton();
JButton settings = new JButton();
JButton exit = new JButton("Exit");

JTextArea space1 = new JTextArea();

JPanel topMenu = new JPanel();
JButton X = new JButton();

JLabel space = new JLabel();

JLabel p2 = new JLabel();

public Image player1 = ImageIO.read(new File("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\tempdude.png"));

ImageIcon window = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\basketball dude.PNG");
ImageIcon gif = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\Ballerz.gif");
ImageIcon court = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\court.png");
ImageIcon player1s = new ImageIcon("C:\\Users\\Adam\\Downloads\\JavaCode\\Ballerz\\src\\tempdude.png");

public FlowLayout flow = new FlowLayout();
public BorderLayout bord = new BorderLayout();
public GridLayout grid = new GridLayout(6, 1);

JLabel ply1 = new JLabel();
JLabel ply2 = new JLabel();

public Game() throws IOException {
    game.setLayout(bord);
    game.setPreferredSize(new Dimension(1366, 768));
    JLabel cort = new JLabel();
    cort.setSize(new Dimension(1366, 768));
    cort.setIcon(court);

    players.setOpaque(false);
    players.setLayout(bord);
    players.setBackground(Color.pink);

    ply1.setIcon(player1s);
    ply1.setSize(new Dimension(200, 200));
    ply1.setVisible(true);
    ply1.setBackground(Color.black);
    ply2.setIcon(player1s);
    ply2.setSize(new Dimension(200, 200));
    ply2.setVisible(true);
    ply2.setBackground(Color.black);
    players.add(ply1);
    players.add(ply2);
    players.setSize(new Dimension(1340, 820));
    players.repaint();
    players.setLayout(null);
    ply2.setLocation(15, 410);
    ply1.setLocation(1230, 410);
    players.repaint();
    players.setVisible(true);
    players.setAlignmentX(CENTER_ALIGNMENT);
    
    game.add(cort, bord.CENTER,5);
    game.add(players,0);
    players.setLocation(0, -50);
    
    game.repaint();
    
}



public static void main(String[] arg) throws Exception {
    GraphicsPn g = new GraphicsPn();
    Game game = new Game();
    keys li = new keys();
}


}

key binds:

package Ballerz;

import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.*;
public class keys extends Game{

public keys() throws IOException {
    
    
    AbstractAction wAction = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("BOI");
            
            if (ply2.getLocation().getY() <= 650 && ply2.getLocation().getY() >= 10) {
                ply2.setLocation((int) ply2.getLocation().getX(), (int) ply2.getLocation().getY() + 10);
                
                System.out.println(ply2.getLocation());
            } 
                if (ply2.getLocation().getY() > 650)
                    ply2.setLocation((int) ply2.getLocation().getX(), 650);
                    players.repaint();
            
            if (ply2.getLocation().getY() < 10) {
                ply2.setLocation((int) ply2.getLocation().getX(), 10);
                players.repaint();
            }
            players.repaint();
        
        }
    };
    
    players.getInputMap().put(KeyStroke.getKeyStroke('w'), "wAction");
    players.getActionMap().put("wAction", wAction );
    
}
}
  • Hi, interesting, does it give an error? – IronMan Nov 17 '20 at 00:52
  • Ok, so the most common issue is going to be related to how `KeyListener` works and would likely be related to just about every other question about "why does my `KeyListener` not work". The most common answer is to use the [key bindings API](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) instead, which will give you more control over when the key event should be triggered – MadProgrammer Nov 17 '20 at 00:55
  • `setSize` should be avoid; `doLayout`, in you case is most probably pointless – MadProgrammer Nov 17 '20 at 00:57
  • Sorry, did't quite scroll all the way to the bottom. When using key bindings, the default operation is executed when the component itself has focus. You can have a look at [`public final InputMap getInputMap​(int condition)`](https://docs.oracle.com/javase/10/docs/api/javax/swing/JComponent.html#getInputMap(int)) to fine tune when the action should be triggered – MadProgrammer Nov 17 '20 at 00:58

1 Answers1

1

You claim that your key bindings aren't working which implies that the only relevant part of the huge amount of code that you posted in your question, are the last two lines, namely

players.getInputMap().put(KeyStroke.getKeyStroke('w'), "wAction");
players.getActionMap().put("wAction", wAction );

where players is a JPanel.

So basically your question boils down to:

Key bindings for JPanel not working

This question has been asked and answered many times on stackoverflow
Try searching the Internet with Google for the terms

jpanel key bindings site:stackoverflow.com

The first result (of more than 2000) was JPanel doesn't react to KeyBindings

Basically you need to

  1. Make sure that players is focusable because, by default, a JPanel is not.
  2. Make sure to use the correct input map
Abra
  • 19,142
  • 7
  • 29
  • 41