如何使用键绑定使矩形在屏幕上移动? [英] How do I make a rectangle move across the screen with key bindings?

查看:18
本文介绍了如何使用键绑定使矩形在屏幕上移动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建的游戏是蛇,到目前为止我已经想出了如何使用 paint(Graphics g) 一些 JPanel,鼠标监听器现在我正在尝试创建一个将在屏幕上移动并使用键绑定或键侦听器的矩形,但我不知道我应该怎么做.

到目前为止,这是我的代码,它有 2 个部分.第一部分称为 snake2 因为如果我不知道我在做什么,我会用不同的东西制作相同的程序.Snake 使用框架,但 Snake2 使用 JPanel(看起来更好……)

 import java.awt.*;//需要鼠标监听器导入 java.awt.event.*;//需要Graohics导入 java.applet.*;导入 javax.swing.*;公共类 Snake2 扩展了 JPanel{私有矩形示例对象;公共 Snake2(){addMouseListener(new MouseListener());}/* 创建背景 */公共空隙油漆(图形g){Font angel = new Font("天使战争", Font.BOLD, 60);Font ith = new Font("Ithornît", Font.BOLD, 78);setBackground(Color.darkGray);g.setColor(Color.darkGray);g.fillRect(0,0,700,850);g.setColor(Color.gray);g.fillRect(50,150,600,650);g.setColor(Color.white);g.drawRect(50,150,600,650);g.drawString("退出",52,116);g.drawRect(50,100,30,20);//g.setFont(angel);//g.drawString("SNAKE",300,70);g.setFont(ith);g.drawString("SNAKE",280,90);}公共无效精灵(int x,int y,图形g){g.setColor(Color.white);g.fillRect(300,200,10,10);}公共无效开始(int x,int y,图形g){g.setColor(Color.white);g.drawString("开始游戏",300,425);}}/* 跟踪鼠标点击的位置 */类 MouseListener 扩展了 MouseAdapter{public void mouseReleased(MouseEvent me){如果 (me.getX() >= 50 && me.getX() <= 80 && me.getY() >= 100 && me.getY() <= 120){System.exit(0);}String str="鼠标发布于 "+me.getX()+","+me.getY();System.out.println(str);}}

第二部分是:

 import javax.swing.JFrame;导入 java.awt.Dimension;公开课 SnakeDisplay{public static void main(字符串[]参数){JFrame frame = new JFrame ("Snake");Snake2 面板 = 新的 Snake2 ( );frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );frame.add ( 面板 );frame.setContentPane ( 面板 );frame.setPreferredSize ( new Dimension ( 700, 850 ) );//frame.setLocationRelativeTo ( null );frame.setVisible ( true );框架包( );}}

解决方案

  1. 您应该覆盖 JPanel 中的 paintComponent 并在其中调用 super.paintComponent(g).
  2. 请参阅

    The game I'm trying to create is snake and so far I've figured out how to use paint(Graphics g) a bit of JPanel, mouse listener and now I'm trying to create a rectangle that will move across the screen and use key bindings or key listener, but I have no idea how I should go about this.

    Here's my code so far, it has 2 parts. The first part is called snake2 because if I don't know what I'm doing I make the same program with different things. Snake used frame, but Snake2 uses JPanel (looks better…)

        import java.awt.*;
    
        //required for MouseListener
        import java.awt.event.*;
    
        //requied for Graohics
        import java.applet.*;
        import javax.swing.*;
    
        public class Snake2 extends JPanel
        {
          private Rectangle sampleObject;
    
          public Snake2()
          {
             addMouseListener(new MouseListener());
    
          }
    
    
          /* create background */
          public void paint (Graphics g)
          {
            Font angel = new Font("Angelic War", Font.BOLD, 60);
            Font ith = new Font("Ithornît", Font.BOLD, 78);
    
            setBackground(Color.darkGray);
            g.setColor(Color.darkGray);
            g.fillRect(0,0,700,850);
            g.setColor(Color.gray);
            g.fillRect(50,150,600,650);
            g.setColor(Color.white);
            g.drawRect(50,150,600,650);
    
            g.drawString("Quit",52,116);
            g.drawRect(50,100,30,20);
    
            //g.setFont(angel);
            //g.drawString("SNAKE",300,70);
            g.setFont(ith);
            g.drawString("SNAKE",280,90);  
          }
    
          public void sprite (int x, int y, Graphics g){
            g.setColor(Color.white);
            g.fillRect(300,200,10,10);
          }
    
          public void start (int x, int y, Graphics g){
            g.setColor(Color.white);
            g.drawString("START GAME",300,425);
          }
        }
    
    
        /* Tracks where mouse is clicked */
        class MouseListener extends MouseAdapter
        {
          public void mouseReleased(MouseEvent me)
          {
            if (me.getX() >= 50 && me.getX() <= 80 && me.getY() >= 100 && me.getY() <= 120)
            {
              System.exit(0);
            }
    
              String str="Mouse Released at "+me.getX()+","+me.getY();
              System.out.println(str);
          }
        }
    

    And the second part is:

        import javax.swing.JFrame;
        import java.awt.Dimension;
    
        public class SnakeDisplay
        {
    
          public static void main ( String [ ] arguments )
          {   
            JFrame frame = new JFrame ( "Snake" );
            Snake2 panel = new Snake2 ( );
    
    
            frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
            frame.add ( panel );
            frame.setContentPane ( panel );
    
            frame.setPreferredSize ( new Dimension ( 700, 850 ) );
            //frame.setLocationRelativeTo ( null );
            frame.setVisible ( true );
            frame.pack ( );     
          }
        }
    

    解决方案

    1. You should override paintComponent in your JPanel and call super.paintComponent(g) in it.
    2. See How to Use Key Bindings tutorial. Key bindings are preffered in this case rather than a KeyListener
    3. pack() then setVisible()
    4. You should set global variables for x anf y location, so they can be accessed from within your Action. Then in your actions, increment your x or y and repaint

    Try running this example

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class KeyBidings extends JFrame {
        int x = 0;
        int y = 0;
    
        DrawPanel drawPanel = new DrawPanel();
    
        public KeyBidings(){
            Action rightAction = new AbstractAction(){
                public void actionPerformed(ActionEvent e) {
                    x +=10;
                    drawPanel.repaint();
                }
            };
    
                InputMap inputMap = drawPanel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
                ActionMap actionMap = drawPanel.getActionMap();
    
            inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "rightAction");
            actionMap.put("rightAction", rightAction);
    
            add(drawPanel);
    
            pack();
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLocationRelativeTo(null);
            setVisible(true);
        }
    
        private class DrawPanel extends JPanel {
    
    
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.GRAY);
                        g.fillRect(0, 0, getWidth(), getHeight());
                g.setColor(Color.GREEN);
                g.fillRect(x, y, 50, 50);
            }
    
            public Dimension getPreferredSize() {
                return new Dimension(400, 200);
            }
        }
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable(){
                public void run(){
                    new KeyBidings();
                }
            });
        }
    }
    

    Here's the code you're more concerned with

        Action rightAction = new AbstractAction(){
            public void actionPerformed(ActionEvent e) {
                x +=10;
                drawPanel.repaint();
            }
        };
    
        InputMap inputMap = drawPanel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = drawPanel.getActionMap();
    
        inputMap.put(KeyStroke.getKeyStroke("RIGHT"), "rightAction");
        actionMap.put("rightAction", rightAction);
    

    Create a custom action and add that action to the action map, linked to the input map keystroke. In the action, just increment or, decrement the x and/or y, depending on the direction, then repaint the panel.


    See Key binding tutorial | Graphics tutorial

    这篇关于如何使用键绑定使矩形在屏幕上移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆