0

Hi am new to programming and am trying to make a game with a start menu and then if you click "start" the screen clears and shows a rect in a black background that you can move around the screen with VK up/down/left/right.

But every time i click start i have to click outside of the window and then back the window for the rect to move around

I have tried to use getContentPane to add panel to the window but still every time i click start have to click outside and then back in the window to move the rect.

Help, what do i need to fix/add to not click outside of the frame and the back again to move the rect around

Heres my code the menu screen :

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

    public class Menuscreen {

        private int WIDTH = 800;
        private int HEIGHT = 600;

    public  void menuscreen () {

            //Window
        final JFrame window = new JFrame();
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(WIDTH, HEIGHT);
        window.setResizable(false);
        window.setLocationRelativeTo(null);


            //Panel
        final JPanel panel = new JPanel();
        panel.setBackground(Color.BLACK);
        panel.setVisible(true);

        panel.setLayout(null);



        window.add(panel);


            //Title 
        JLabel label = new JLabel("SNAKE");
        panel.add(label);
        label.setBounds(290, 5, 204, 73);
        label.setFont(new Font("Tahoma", Font.BOLD, 60));
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setForeground(Color.RED);
        label.setBackground(Color.red);

            //Buttons
            //start button
        JButton bstart = new JButton ("Start");
        panel.add(bstart);
        bstart.setBounds(424, 200, 70, 60);
        bstart.setVisible(true);

        //start button - run snake on click
        bstart.addActionListener(new ActionListener() 
              {
                public void actionPerformed(ActionEvent e)
            {

            window.getContentPane().remove(panel);

            snake snake = new snake();
            window.add(snake);


          window.revalidate();
          window.repaint();


       }
              });

            //exit button
        JButton bexit = new JButton ("Exit");
        panel.add(bexit);
        bexit.setBounds(290, 200, 70, 60);
        bexit.setVisible(true);
            //exit button - close on click
        bexit.addActionListener(new ActionListener() 
              {
                public void actionPerformed(ActionEvent e)
            {
                System.exit(0);
            }
              });

    }
}

and the snake class:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;

import javax.swing.JPanel;
import javax.swing.Timer;


   public class snake extends  JPanel implements ActionListener, KeyListener {



    public void thicks () {}

   public snake () {

     setBackground(Color.BLACK);

     addKeyListener(this);
     setFocusable(true);
     setFocusTraversalKeysEnabled(false);

    //thread = new Thread(this);
//  thread.start();

    }



    private static final long serialVersionUID = 1L;


    Timer fps = new Timer( 5, this);
    double x =0 , y = 0, speedx = 0, speedy = 0;



    public void paintComponent(Graphics g) {
        fps.start();
        super.paintComponent(g);
        g.setColor(Color.blue);
        Graphics2D graphics  = (Graphics2D) g;

        Rectangle2D rect = new Rectangle2D.Double(x, y, 40, 40);
        graphics.fill(rect);


        }

    public void actionPerformed(ActionEvent e) {    
    if(x < 0 ||  x > 740 ) {
        speedx= -speedx;
    }

    if(y < 0 || y > 520) {
        speedy = -speedy;
            }

    x += speedx;
    y += speedy;
    repaint();
}

    public void down() {
        speedy = 2;
        speedx =  0;

    }

    public void up() {
        speedy = -2;
        speedx = 0;     
    }

    public void right() {
        speedy = 0;
        speedx = 2; 

    }

    public void left() {
        speedy =  0;
        speedx = -2;    
    }

    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();

        if (keyCode == KeyEvent.VK_DOWN) {
            down();
         }

        if(keyCode == KeyEvent.VK_UP) {
            up();
        }

        if(keyCode == KeyEvent.VK_RIGHT) {
            right();
        }

        if(keyCode == KeyEvent.VK_LEFT) {
            left();
        }

    }

    public void keyReleased(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}

    public void run() {


    }



   }

lastly the main

public class Main {
public static void main(String [] args) {
    Menuscreen Menuscreen = new Menuscreen();
        Menuscreen.menuscreen();
            }
                }
  • You have hit the famous "focus related issue" of which `KeyListener` suffers from (a little bit of googling would have highlighted the issue). While there are a plenty of "hacks", the only real solution is to make use of the [key bindings API](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) instead of `KeyListener` – MadProgrammer Mar 21 '19 at 06:35
  • I have been looking for it but the stuff i tried dont work, could u show me an example? – Melkree Mar 21 '19 at 18:58
  • [Example](https://stackoverflow.com/questions/22748547/java-swing-timer-only-works-once-then-keyevents-fire-in-rapid-succession-holdi/22749251#22749251); [example](https://stackoverflow.com/questions/51352161/how-to-stop-flickering-in-java-awt-graphics/51352368#51352368); [example](https://stackoverflow.com/questions/34125578/gradually-accelerate-sprite-on-key-pressed-gradually-decelerate-on-key-released/34126260#34126260); – MadProgrammer Mar 21 '19 at 21:00

0 Answers0