Помещение KeyListener внутри ActionListener - PullRequest
0 голосов
/ 19 сентября 2019

Я делаю простую игру-лабиринт и пытаюсь создать для нее главное меню.По сути, всякий раз, когда нажимается JButton, вызывается ActionListener, и создается новое окно с игрой внутри него.внутри игры есть KeyListener, так что вы можете перемещаться с помощью клавиш со стрелками.Однако, когда я запускаю его, клавиши со стрелками не работают, и кнопка остается нажатой.Вот код для MainMenu:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class MainMenu extends JFrame
{
    private int timer;
    private JLabel Timer;
    public MainMenu(String title, int width, int height){
        JButton maze1 = new JButton("Maze 1");
        JButton maze2 = new JButton("Maze 2");
        JButton maze3 = new JButton("Maze 3");
        JButton maze4 = new JButton("Maze 4");
        JButton maze5 = new JButton("Maze 5");
        JLabel instructions = new JLabel();
        instructions.setText("Pick a maze!");
        Timer = new JLabel();
        Timer.setBounds(0, 150, 220, 20);
        Timer.setText("0.0");

        maze1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0){
                try{playMaze(1);}catch(FileNotFoundException e){}
            }
        });
        maze2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0){
                try{playMaze(2);}catch(FileNotFoundException e){}
            }
        });
        maze3.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0){
                try{playMaze(3);}catch(FileNotFoundException e){}
            }
        });
        maze4.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0){
                try{playMaze(4);}catch(FileNotFoundException e){}
            }
        });
        maze5.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent arg0){
                try{playMaze(5);}catch(FileNotFoundException e){}
            }
        });

        add(instructions);
        add(maze1);
        add(maze2);
        add(maze3);
        add(maze4);
        add(maze5);

        setTitle(title);
        setLayout(new FlowLayout());
        setSize(width, height);

        timer = 0;
    }

    public void playMaze(int i) throws FileNotFoundException{
        MazeCreator creator = new MazeCreator();
        creator.createMaze("MAZE" + i + ".txt");
        MazeRunner runner = new MazeRunner(creator.getMaze(), 0, 5, timer);
        runner.run();
        timer = runner.getTime();
        Timer.setText("" + timer/10.0);
    }
}

MazeRunner:

import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class MazeRunner implements Runnable
{
    private JFrame frame;
    private Canvas canvas;
    private BufferStrategy bufferStrategy;

    private String[][] maze;
    private int x;
    private int y;
    private boolean win;
    private int timer;

    public MazeRunner(String[][] Maze, int Y, int X, int t){
        frame = new JFrame("Maze Game");
        JPanel panel = (JPanel) frame.getContentPane();
        panel.setPreferredSize(new Dimension(220, 250));
        panel.setLayout(null);
        canvas = new Canvas();
        canvas.setBounds(0, 0, 220, 250);
        canvas.setIgnoreRepaint(true);
        panel.add(canvas);
        canvas.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent evt) {
                move(evt);
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setResizable(false);
        frame.setVisible(true);
        canvas.createBufferStrategy(2);
        bufferStrategy = canvas.getBufferStrategy();
        canvas.requestFocus();

        maze = Maze;
        x = X;
        y = Y;
        maze[y][x] = "@";
        win = false;
        timer = t;
    }

    public boolean checkWin(){return win;}

    public void run(){

        while(!win){
            Paint();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
            timer++;
        }
        maze[y][x] = "@";
        Paint();
        try{Thread.sleep(1000);}catch(InterruptedException e){}
        frame.dispose();
    }

    public void move(KeyEvent evt) {
        switch (evt.getKeyCode()) {
            case KeyEvent.VK_DOWN:
                moveDown();
                break;
            case KeyEvent.VK_UP:
                moveUp();
                break;
            case KeyEvent.VK_LEFT:
                moveLeft();
                break;
            case KeyEvent.VK_RIGHT:
                moveRight();
                break;
        }
    }

    public void moveUp(){
        maze[y][x] = "-";
        if(!(y > 0)){
        }else if(maze[y - 1][x].equals("*")){
        }else if(maze[y - 1][x].equals("#")){
            y -= 1;
            win = true;
        }else{
            y -= 1;
        }
        maze[y][x] = "@";
    }

    public void moveDown(){
        maze[y][x] = "-";
        if(!(y < 10)){
        }else if(maze[y + 1][x].equals("*")){
        }else if(maze[y + 1][x].equals("#")){
            y += 1;
            win = true;
        }else{
            y += 1;
        }
        maze[y][x] = "@";
    }

    public void moveLeft(){
        maze[y][x] = "-";
        if(!(x > 0)){
        }else if(maze[y][x - 1].equals("*")){
        }else if(maze[y][x - 1].equals("#")){
            x -= 1;
            win = true;
        }else{
            x -= 1;
        }
        maze[y][x] = "@";
    }

    public void moveRight(){
        maze[y][x] = "-";
        if(!(x < 10)){
        }else if(maze[y][x + 1].equals("*")){
        }else if(maze[y][x + 1].equals("#")){
            x += 1;
            win = true;
        }else{
            x += 1;
        }
        maze[y][x] = "@";
    }

    public void printMaze(){
        System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
        for(int i = 0; i < 11; i++){
            for(int e = 0; e < 11; e++){
                System.out.print(maze[i][e] + " ");
            }
            System.out.println();
        }
    }

    public void Paint() {
        Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
        g.clearRect(0, 0, 500, 500);
        Paint(g);
        bufferStrategy.show();
    }

    protected void Paint(Graphics2D g) {
        for(int i = 0; i < 11; i++){
            for(int e = 0; e < 11; e++){
                if(maze[i][e].equals("*")){
                    g.setColor(Color.BLACK);
                    g.fillRect(e*20, i*20, 20, 20);
                }else if(maze[i][e].equals("@")){
                    g.setColor(Color.RED);
                    g.fillOval(e*20, i*20, 20, 20);
                }else if(maze[i][e].equals("#")){
                    g.setColor(Color.BLUE);
                    g.fillRect(e*20, i*20, 20, 20);
                }
            }
        }
        g.setColor(Color.BLACK);
        g.drawString("" + (timer / 10.0), 190, 240);
        if(win){
            g.setFont(new Font("Dialouge", Font.BOLD, 20));
            g.drawString("YOU WIN!", 10, 240);
        }
    }

    public String mazeToString(int y){
        String toString = "";
        for(int e = 0; e < 11; e++){
            toString += maze[y][e] + " ";
        }
        return toString;
    }

    public int getTime(){return timer;}
}

И MazeCreator:

import java.util.*;
import java.io.*;

public class MazeCreator
{
    private String[][] maze;
    private int xPos;
    private int yPos;
    private File file;
    private Scanner input;

    public MazeCreator(){
        maze = new String[11][11];
    }

    public String[][] getMaze(){return maze;}

    public void createMaze(String File) throws FileNotFoundException{
        input = new Scanner(new File("C:/Users/Owner/Maze/" + File));
        for(int i = 0; i < 11; i++){
            for(int e = 0; e < 11; e++){
                maze[i][e] = input.next();
                //System.out.print(maze[i][e] + " ");
            }
            input.nextLine();
            //System.out.println();
        }
    }
}

Любая помощь, которую кто-либо может оказать, будетбольшой.

...