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

时间:2013-12-30 17:09:02

标签: java swing graphics awt paint

我正在尝试创建的游戏是蛇,到目前为止,我已经弄清楚如何使用paint(Graphics g)一点JPanel,鼠标监听器,现在我正在尝试创建一个矩形它将在屏幕上移动并使用键绑定或关键监听器,但我不知道应该如何解决这个问题。

这是我的代码到目前为止,它有2个部分。 第一部分称为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 ( );     
      }
    }

1 个答案:

答案 0 :(得分:5)

  1. 您应该覆盖paintComponent中的JPanel并在其中调用super.paintComponent(g)
  2. How to Use Key Bindings tutorial。在这种情况下,键绑定优先于KeyListener
  3. pack() 然后 setVisible()
  4. 您应该为x anf y location设置全局变量,以便可以从Action中访问它们。然后在您的操作中,增加x或y并重新绘制
  5. 尝试运行此示例

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

    enter image description here

    以下是您更关注的代码

        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