我正在尝试使用KeyListener来移动图像,但这给我一个错误? [英] I'm trying to make my image move using KeyListener but it's giving me an error?

查看:66
本文介绍了我正在尝试使用KeyListener来移动图像,但这给我一个错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让Boy1移动,但在第二堂课中,我在setX下得到了红线.有人知道怎么了吗?

I'm trying to make Boy1 move but in the second class I'm getting redlines under setX. Anyone know what's wrong?

头等舱

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class MyGame extends JPanel implements ActionListener, KeyListener {
    Timer t = new Timer(5, this);
    int x = 0, y = 0, velx =0, vely =0;

    public MyGame() {
        t.start();
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.fillRect(x,y,50,30);
    }

    public void actionPerformed(ActionEvent e) {
        if(x < 0)
        {
            velx=0;
            x = 0;  
        }

        if(x > 530)
        {
            velx=0;
            x = 530;    
        }

        if(y < 0)
        {
            vely=0;
            y = 0;  
        }

        if(y > 330)
        {
            vely=0;
            y = 330;    
        }

        x += velx;
        y += vely;
        repaint();
    }

    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();

        if (code == KeyEvent.VK_DOWN){
            vely = 1;
            velx = 0;
        }
        if (code == KeyEvent.VK_UP){
            vely = -1;
            velx = 0;
        }
        if (code == KeyEvent.VK_LEFT){
            vely = 0;
            velx = -1;
        }
        if (code == KeyEvent.VK_RIGHT){
            vely = 0;
            velx = 1;
        }
    }
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {
        velx=0;
        vely=0;
    }


    public static void main (String arge[]){

        JFrame f = new JFrame();
        MyGame s = new MyGame();
        f.add(s);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(600,400);
        f.setVisible(true);

    }
}

最后一堂课的问题.也许需要KeyAdapter吗?但是我尝试过,似乎完全不起作用.

Problem is with this last class. Perhaps it needs to be KeyAdapter? But I tried that and seems like that totally doesn't work.

推荐答案

编译器出于某种原因对您进行标记-您试图在变量上调用方法,就好像它是类所包含的变量一样.不是-它是由另一个班级持有的.这不是Java中的犹太洁食.

The compiler is flagging you for a reason -- you're trying to call methods on a variable as if it were a variable that the class contains when it isn't -- it's held by a different class. And this isn't Kosher in Java.

您应该做的是提供一个类,该类包含外部类可以调用的变量公共方法,并使外部类能够移动标签.然后,为您的控制对象(侦听器)提供具有这些方法的类的实例.

What you should do is give the class that holds the variable public methods that outside classes can call and that will allow outside classes to be able to move the label. Then give your control object (the listener) an instance of the class that has these methods.

顺便说一句,通常最好使用键绑定"而不是"KeyListener".

As an aside, you're usually better off using Key Bindings and not using a KeyListener.

我可以举一个使用键绑定在JPanel上移动JLabel的代码示例:

I can give you an example of code that uses Key Bindings to move a JLabel around a JPanel:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.EnumMap;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class AnimateExample extends JPanel {
   public static final String DUKE_IMG_PATH = // https://duke.kenai.com/iconSized/duke.gif
         "https://duke.kenai.com/iconSized/duke4.gif";
   private static final int PREF_W = 800;
   private static final int PREF_H = 800;
   private static final int TIMER_DELAY = 20;
   private static final String KEY_DOWN = "key down";
   private static final String KEY_RELEASE = "key release";
   public static final int TRANSLATE_SCALE = 3;
   private static final String BACKGROUND_STRING = "Use Arrow Keys to Move Image";
   private static final Font BG_STRING_FONT = new Font(Font.SANS_SERIF,
         Font.BOLD, 32);
   private EnumMap<Direction, Boolean> dirMap = 
         new EnumMap<AnimateExample.Direction, Boolean>(Direction.class);
   private BufferedImage image = null;
   private int imgX = 0;
   private int imgY = 0;
   private int bgStringX; 
   private int bgStringY; 

   public AnimateExample() {
      for (Direction dir : Direction.values()) {
         dirMap.put(dir, Boolean.FALSE);
      }
      try {
         URL imgUrl = new URL(DUKE_IMG_PATH);
         image = ImageIO.read(imgUrl);
         Icon icon = new ImageIcon(image);
         JOptionPane.showMessageDialog(null, icon);
      } catch (MalformedURLException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }

      new Timer(TIMER_DELAY, new TimerListener()).start();

      // here we set up our key bindings
      int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();
      for (final Direction dir : Direction.values()) {

         // for the key down key stroke
         KeyStroke keyStroke = KeyStroke.getKeyStroke(dir.getKeyCode(), 0,
               false);
         inputMap.put(keyStroke, dir.name() + KEY_DOWN);
         actionMap.put(dir.name() + KEY_DOWN, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
               dirMap.put(dir, true);
            }
         });

         // for the key release key stroke
         keyStroke = KeyStroke.getKeyStroke(dir.getKeyCode(), 0, true);
         inputMap.put(keyStroke, dir.name() + KEY_RELEASE);
         actionMap.put(dir.name() + KEY_RELEASE, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
               dirMap.put(dir, false);
            }
         });
      }

      FontMetrics fontMetrics = getFontMetrics(BG_STRING_FONT);
      int w = fontMetrics.stringWidth(BACKGROUND_STRING);
      int h = fontMetrics.getHeight();

      bgStringX = (PREF_W - w) / 2;
      bgStringY = (PREF_H - h) / 2;
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g.setFont(BG_STRING_FONT);
      g.setColor(Color.LIGHT_GRAY);
      g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
      g.drawString(BACKGROUND_STRING, bgStringX, bgStringY);

      if (image != null) {
         g.drawImage(image, imgX, imgY, this);
      }
   }

   private class TimerListener implements ActionListener {
      public void actionPerformed(java.awt.event.ActionEvent e) {
         for (Direction dir : Direction.values()) {
            if (dirMap.get(dir)) {
               imgX += dir.getX() * TRANSLATE_SCALE;
               imgY += dir.getY() * TRANSLATE_SCALE;
            }
         }
         repaint();
      };
   }

   enum Direction {
      Up(KeyEvent.VK_UP, 0, -1), Down(KeyEvent.VK_DOWN, 0, 1), Left(
            KeyEvent.VK_LEFT, -1, 0), Right(KeyEvent.VK_RIGHT, 1, 0);

      private int keyCode;
      private int x;
      private int y;

      private Direction(int keyCode, int x, int y) {
         this.keyCode = keyCode;
         this.x = x;
         this.y = y;
      }

      public int getKeyCode() {
         return keyCode;
      }

      public int getX() {
         return x;
      }

      public int getY() {
         return y;
      }

   }

   private static void createAndShowGui() {
      AnimateExample mainPanel = new AnimateExample();

      JFrame frame = new JFrame("Animate Example");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

这篇关于我正在尝试使用KeyListener来移动图像,但这给我一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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