Вопрос по java, swing – Как я могу использовать KeyListener в Java?

1

Как использовать KeyListener в этом коде для перемещения вверх и вниз? Я знаю, как использовать KeyListener, но я не знаю, где он помещен в этот код.

    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.awt.geom.*;

    import javax.swing.*;


    public class ControlPanel extends JPanel implements Runnable,ActionListener,KeyListener,MouseListener{
        private MainPanel main;
        private final static int maxWidth = 800, maxHeight = 600; //width & height of JPanel
        private boolean running; //keeps track of state of the program
        private Thread thread;
        private Graphics2D graphics;
        private Image image; //used for double buffering
        private BufferedImage bgImage;
        private String s = "";
        Font f = new Font("Times New Roman",Font.PLAIN,50);
        Timer t = new Timer(2000,this);
        private int typed = 0;
        private int x = 50,y = 500;

        public ControlPanel(MainPanel main) {
            this.setDoubleBuffered(false); //we'll use our own double buffering method
            this.setBackground(Color.black);
            this.setPreferredSize(new Dimension(maxWidth, maxHeight));
            this.setFocusable(true);
            this.requestFocus();
            this.main = main;
            addKeyListener(this);
            addMouseListener(this);
            t.start();
        }

        public static void main(String[] args) {
            new MainPanel();
        }

        public void addNotify() {
            super.addNotify();
            startGame();
        }

        public void stopGame() {
            running = false;
        }

        //Creates a thread and starts it
        public void startGame() {
            if (thread == null || !running) {
                thread = new Thread(this);
            }
            thread.start(); //calls run()
        }

        public void run() {
            running = true;

            init();
            while (running) {
                createImage(); //creates image for double buffering

                ///////////////USE THESE 2 METHODS////////////////////
                update(); //use this to change coordinates, update values, etc


                draw(); //use this to draw to the screen


                //////////////////////////////////////////////////////
                drawImage(); //draws on the JPanel
            }

            System.exit(0);
        }





        //Use this to create or initialize any variables or objects you have
        public void init() {
        }
         public void initGame(){

         }



        //Use this to update anything you need to update
        public void update() {

        }

        //Use this to draw anything you need to draw
        public void draw() {        

            graphics.setColor(Color.WHITE);
            graphics.fillRect(250, 450, 300,100);

            graphics.setColor(Color.WHITE);
            graphics.fillRect(250, 320, 300,100);

            graphics.setColor(Color.GREEN);
            graphics.setFont(f);
            graphics.drawString(s, x, y);
            typed = 0;

            graphics.setFont(f);
            graphics.setColor(Color.blue);
            graphics.drawString("HANGMAN", 270,75);

            graphics.setFont(f);
            graphics.setColor(Color.blue);
            graphics.drawString("PLAY", 330, 390);

            graphics.setFont(f);
            graphics.setColor(Color.blue);
            graphics.drawString("QUIT", 330, 520);

            graphics.setColor(Color.red);
            graphics.drawRect(248, 318, 304,104);




        }

        //creates an image for double buffering
        public void createImage() {
            if (image == null) {
                image = createImage(maxWidth, maxHeight);

                if (image == null) {
                    System.out.println("Cannot create buffer");
                    return;
                }
                else
                    graphics = (Graphics2D)image.getGraphics(); //get graphics object from Image
            }

            if (bgImage == null) {
                graphics.setColor(Color.black);
                graphics.fillRect(0, 0, maxWidth, maxHeight);
                //System.out.println("No background image");
            }
            else {
                //draws a background image on the Image
                graphics.drawImage(bgImage, 0, 0, null);
            }
        }

        //outputs everything to the JPanel
        public void drawImage() {
            Graphics g;
            try {
                g = this.getGraphics(); //a new image is created for each frame, this gets the graphics for that image so we can draw on it
                if (g != null && image != null) {
                    g.drawImage(image, 0, 0, null);
                    g.dispose(); //not associated with swing, so we have to free memory ourselves (not done by the JVM)
                }
                image = null;
            }catch(Exception e) {System.out.println("Graphics objects error");}
        }


        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub

        }

        public void keyPressed(KeyEvent e) {    



        }

        public void keyReleased(KeyEvent e) {


        }

        public void keyTyped(KeyEvent e) {
            typed = 1;

            s+=Character.toString(e.getKeyChar());
            s+=" ";
            System.out.println(s);
        }

        @Override



        public void mouseClicked(MouseEvent e) {
            System.out.println(e.getPoint());

        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mousePressed(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseReleased(MouseEvent arg0) {
            // TODO Auto-generated method stub

        }
    }
Судя по всему, и, как вы упомянули, это Swing, так что решите пройтись по учебникамKeyBindingKeyListeners не подходят, я думаю, так как вы просто хотели двигаться вверх и вниз :-) nIcE cOw
Посмотри на этоcode example nIcE cOw

Ваш Ответ

2   ответа
2

KeyListener не предназначен для прослушивания событий клавиатуры дляSwing JComponentsиспользоватьКомбинации клавиш вместо этого вывод в графический интерфейс Swing должен быть изСвинг Действие

2

& # XA0; & # XA0;

addKeyListener(this);

Похожие вопросы