【问题标题】:How do I make a rectangle move across the screen with key bindings?如何使用键绑定使矩形在屏幕上移动?
【发布时间】:2014-01-17 14:39:02
【问题描述】:

我正在尝试创建的游戏是蛇,到目前为止,我已经弄清楚如何使用 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 ( );     
      }
    }

【问题讨论】:

  • 您具体要问什么?如何循环一些游戏逻辑让蛇移动?
  • 看看Performing Custom Painting教程是否回答了你的问题。
  • 如果您将其改写为更具体,则该问题具有潜力,但现在它有被关闭的危险。我认为它可以恢复。

标签: java swing graphics awt paint


【解决方案1】:
  1. 您应该在 JPanel 中覆盖 paintComponent 并在其中调用 super.paintComponent(g)
  2. How to Use Key Bindings tutorial。在这种情况下,首选键绑定而不是 KeyListener
  3. pack() 那么 setVisible()
  4. 您应该为 x anf y 位置设置全局变量,以便可以从您的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

【讨论】:

  • @Muhammad 我刚刚使用CamStudio 捕获屏幕视频,然后将 avi 导入到 photoshop 并以 gif 格式保存到网络
  • +1 for example,请注意您忘记提及或将 JComponent 的焦点设置为 InputMap
  • 绘制是否覆盖了绘制组件?因为每当我使用两个油漆组件时都是不可见的
  • 其实没关系我之前的评论。由于无法同时显示paint和paintComponent,您如何添加背景
  • 什么背景?图片?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多