java – 如何使用键绑定使矩形在屏幕上移动?

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

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

    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);
      }
    }

第二部分是:

    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 ( );     
      }
    }

解决方法:

>您应该覆盖JPanel中的paintComponent并在其中调用super.paintComponent(g).
>请参阅How to Use Key Bindings tutorial.在这种情况下,键绑定优先于KeyListener
> pack()然后setVisible()
>您应该为x anf y location设置全局变量,以便可以在Action中访问它们.然后在你的动作中,增加你的x或y并重新绘制

尝试运行此示例

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();
            }
        });
    }
}

这是你更关心的代码

    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);

创建自定义操作并将该操作添加到操作映射,链接到输入映射键击.在动作中,根据方向增加或减小x和/或y,然后重新绘制面板.

Key binding tutorial | Graphics tutorial

上一篇:Java:在ActionListener中使用图形组件


下一篇:java – 拖放后移动组件