Java cardlayout setting focus on a panel so key listener will work in another class

53 Views Asked by At

I have an issue using Keylistener so I can have things move around on the screen, for now I just make so it print out text so it shows that it works.

The issue is that nothing happens when I press the keys and I do believe it is properly implemented on the board class and the Player class.

I have located the issue to the main class itself where the menu is being set up with card layout. I believe the issue is there is lack of focus on the jPanel3 where the game is gonna be set up.

After changing some of the code to make it runnable but still having the issue. It looks basic but it works for this.

How do I make so the focus is on what happens on/inside jPanel3? In the panel3 method I have left something I have tried but did not fix the issue.

import javax.swing.JFrame;
import java.awt.*; 
import javax.swing.*; 
import java.awt.event.*; 

public class Test extends JFrame implements ActionListener {
    CardLayout crd;
    JButton btn1, btn2, btn3, btn4;
    Container cPane;
    JPanel cPanel = new JPanel();
    JPanel jPanel1,jPanel2,jPanel3;
    Board board = new Board();
    private int currCard = 1;
    GridBagConstraints c = new GridBagConstraints();

    Test() {
        jPanel1 = new JPanel();
        jPanel2 = new JPanel();
        jPanel3 = new JPanel();

        btn1 = new JButton("Start");
        btn2 = new JButton("Help");
        btn3 = new JButton("Back");
        btn4 = new JButton("Exit");

        cPane = getContentPane();
        crd = new CardLayout();
        cPanel.setLayout(crd);

        buttons();
        panel1();
        panel2();
        panel3();

        cPanel.add(jPanel1, "1");
        cPanel.add(jPanel2, "2");
        cPanel.add(jPanel3, "3");

        btn1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                currCard = 3;
                crd.show(cPanel, "" + (currCard));
            }
        });

        btn2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                currCard = 2;
                crd.show(cPanel, "" + (currCard));
            }
        });

        btn3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                currCard = 1;
                crd.show(cPanel, ""+ (currCard));
            }
        });

        btn4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });

        getContentPane().add(cPanel);
    }

    void panel1() {
        jPanel1.setBackground(Color.black);
        jPanel1.setLayout(new GridBagLayout());
        // Set the layout to GridBagLayout
        c.fill = GridBagConstraints.CENTER;
        c.insets = new Insets(15, 0, 0, 0); // Add vertical padding
        jPanel1.add(btn1, c);
        c.gridy = 1;
        jPanel1.add(btn2, c);
        c.gridy = 2;
        jPanel1.add(btn4, c);
    }

    void panel2() {
        JTextArea textField = new JTextArea("Text text");
        textField.setEditable(false);
        textField.setHighlighter(null);
        Font font = new Font("Courier", Font.BOLD, 35);
        textField.setFont(font);      
        textField.setPreferredSize(new Dimension(500, 940));
        textField.setForeground(Color.WHITE);
        textField.setBackground(Color.black);

        jPanel2.setBackground(Color.black);
        jPanel2.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.NORTHWEST; // Align component to the upper left corner
        gbc.insets = new Insets(15, 0, 0, 0); // Add vertical padding
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0; // Expand horizontally
        gbc.weighty = 0.5; // Expand vertically
        jPanel2.add(textField, gbc);
        gbc.gridx = 0;
        gbc.gridy = 1; // Set the grid position for btn3
        gbc.anchor = GridBagConstraints.NORTH; // Align component to the upper left corner
        jPanel2.add(btn3, gbc);
    }

    void panel3() {

        jPanel3.setFocusable(true);
        jPanel3.setRequestFocusEnabled(true);
        jPanel3.setLayout(new BorderLayout(0, 0));
        jPanel3.add(board);
        jPanel3.grabFocus();    
    }

    void buttons() {
        // make the buttons look better and make it so they look good with the background, chane the size of them 
        btn1.setPreferredSize(new Dimension(75, 50));
        btn1.setBackground(Color.black);
        btn1.setForeground(Color.WHITE);

        btn2.setPreferredSize(new Dimension(75, 50));
        btn2.setBackground(Color.black);
        btn2.setForeground(Color.WHITE);

        btn3.setPreferredSize(new Dimension(75, 50));
        btn3.setBackground(Color.black);
        btn3.setForeground(Color.WHITE);

        btn4.setPreferredSize(new Dimension(75, 50));
        btn4.setBackground(Color.black);
        btn4.setForeground(Color.WHITE);
    }

   public static void main(String argvs[]) {
        System.out.println("aaa" + System.getProperty("user.dir")); 
        Test frame = new Test();
        frame.setTitle("Space invaders");
        frame.setSize(900, 900);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        throw new UnsupportedOperationException("Unimplemented method 'actionPerformed'");
    }

}

Crudly put together Board class.

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

public class Board extends JPanel {
    Player player = new Player(50, 50, 50, 50);


    public Board(){
        addKeyListener((KeyListener) player);

        setFocusable(true);
    }

    public void paint(Graphics g) {
        g.setColor(Color.DARK_GRAY);
        g.fillRect(0, 0, 900, 900);
        g.setColor(Color.WHITE);            
        g.drawRect (20, 20, 864, 624);  
        g.setColor(Color.BLACK);
        g.fillRect (21, 21, 863, 623);
        g.setColor(Color.WHITE);    
        g.setFont(new Font("arial",Font.PLAIN,14));
        player.draw(g);
        //repaint();
    }

    public void board(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        Stroke stroke1 = new BasicStroke(4f);
        g2d.setColor(Color.white);
        g2d.setStroke(stroke1);
        g2d.drawRect(20, 50, 850, 600);
        g2d.setColor(Color.white);
        float[] dashingPattern2 = {10f, 4f};
        Stroke stroke2 = new BasicStroke(4f, BasicStroke.CAP_BUTT,
        BasicStroke.JOIN_MITER, 1.0f, dashingPattern2, 0.0f);
        g2d.setStroke(stroke2);
        g2d.drawLine(448, 50, 448, 650);
        g.setFont(new Font("arial",Font.PLAIN,30));
    }


}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;

public class Player extends JPanel implements KeyListener  {

    public int playerXpos;
    public int playerYpos;
    public int playerWidth;
    public int playerHeight;
    public int speed = 2;
    boolean down = false;
    boolean up = false;
    Rectangle player;

    public Player(int playerXpos, int playerYpos, int playerWidth, int playerHeight){
        this.playerXpos = playerXpos;
        this.playerYpos = playerYpos;
        this.playerWidth = playerWidth;
        this.playerWidth = playerHeight;
        player = new Rectangle(playerXpos, playerYpos, playerWidth, playerHeight);
    } 


    protected void draw(Graphics g) {
        playerXpos = 500;
        playerYpos = 60;
        playerWidth = 50;
        playerHeight = 30;
        g.setColor(Color.CYAN);
        g.fillRect(playerXpos, playerYpos, playerWidth, playerHeight);
    }

    @Override
    public void keyPressed(KeyEvent keyCode) {
        if (keyCode.getKeyCode() == KeyEvent.VK_UP) {
            System.out.println("Up Arrrow-Key is pressed!");
        }
        else if (keyCode.getKeyCode() == KeyEvent.VK_DOWN) {
            System.out.println("Down Arrrow-Key is pressed!");
        }
        else if (keyCode.getKeyCode() == KeyEvent.VK_LEFT) {
            System.out.println("Left Arrrow-Key is pressed!");
        }
        else if (keyCode.getKeyCode() == KeyEvent.VK_RIGHT) {
           System.out.println("Right Arrrow-Key is pressed!");
        }    
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'keyReleased'");
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'keyTyped'");
    }
    
}
1

There are 1 best solutions below

3
Jon doe On

Issue is solved. It was rather simple.

        btn1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                currCard = 3;
                crd.show(cPanel, "" + (currCard));
                board.setFocusable(true);
                board.requestFocusInWindow();
            }
        });