我如何与按键绑定在屏幕上一个矩形的举动?我如何与按键绑定在屏幕上一个矩形的举动?(How do I

2019-05-12 10:06发布

我试图创建本场比赛是蛇,到目前为止,我已经想通了如何使用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 ( );     
      }
    }

Answer 1:

  1. 你应该重写paintComponent在您JPanel并调用super.paintComponent(g)在里面。
  2. 请参阅如何使用按键绑定教程 。 键绑定在这种情况下优先停留,而不是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,根据方向,然后重画面板。


请参阅 键绑定教程 | 图形教程



文章来源: How do I make a rectangle move across the screen with key bindings?