将keylistener添加到java中。实现keylistener类限制?

时间:2014-11-08 23:26:04

标签: java eclipse swing keylistener

当我按“w”键时,我试图让这个矩形移动。我想知道为什么eclipse给我一个错误,说变量“hello”没有找到,每当我清楚地将它标记为上面声明的矩形时,它是否在“公共虚空”类中。当我按“w”时它什么也没做。

import java.awt.Graphics;
import java.awt.Graphics2D;    
import javax.swing.JComponent;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.*;

public class drawingComponent extends JComponent implements KeyListener {

    public void paintComponent(Graphics g){
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(new Color(255,25,0));
        g2.setFont(new Font("monospace", Font.BOLD+Font.ITALIC, 30));
        g2.drawString("nothing yet",300,320);
        Rectangle hello = new Rectangle(300, 100, 50, 50);          
        g2.fill(hello);
    }       

    @Override
    public void keyPressed(KeyEvent e) {            
        if(e.getKeyCode() == KeyEvent.VK_W){                
             hello.setLocation(hello.x-50, hello.y);                 
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {        

    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub          
    }    
}

1 个答案:

答案 0 :(得分:0)

变量hello在方法paintComponent()中声明。您需要使其成为类的成员,以使其可用于其他方法,简而言之。