如何使用KeyListeners时访问方法?

时间:2013-12-21 15:23:34

标签: java canvas graphics awt keylistener

大家好!我想用KeyListeners做一些事情,只要按下按钮,就会导致画布重新绘制。但是,问题是由于封装,KeyListener无法访问其他类中的任何方法。解决这个问题的关键是什么?

谢谢!

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class FaceFrame extends JFrame {
    private FaceCanvas face;
    public FaceFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 800);
        setVisible(true);
        setLayout(new BorderLayout());
        KeyListenerTester bob = new KeyListenerTester();
        face = new FaceCanvas();
        face.addKeyListener(bob);
        add(face, BorderLayout.CENTER);
    }

    public static void main(String args[]) {
        JFrame faceFrame = new FaceFrame();
    }

}

class FaceCanvas extends Canvas { 
    private Face whiteGuy;
    private Face redGuy;
    public FaceCanvas() {
        setBackground( Color.BLUE);
        setSize( 800, 800 );

        whiteGuy = new Face(50, 50, 150, 150, Color.WHITE, "White");
        redGuy = new Face(300, 300, 150, 150, Color.RED, "Red");
    }
    public void paint( Graphics g ) { 
        // override paint method by re-defining it
        whiteGuy.paint(g);
        redGuy.paint(g);
        repaint();
    }
}

class Face {
    int xpos, ypos;
    int width, height;
    Color skinTone;
    String tattoo;
    Font f;
    public Face(int xpos, int ypos, int width, int height, Color skinTone, String tattoo) {
        this.xpos = xpos;
        this.ypos = ypos;
        this.width = width;
        this.height = height;
        this.skinTone = skinTone;
        this.tattoo = tattoo;
        f = new Font( "Times New Roman", Font.ITALIC| Font.BOLD, 24 );
    }

    public void paint(Graphics g) {
        g.setColor( skinTone );
        g.drawOval( xpos, ypos, width, height );
        g.drawLine( xpos+ 10, ypos+ height-30, xpos+ width-30, ypos + height- 30 );
        g.setFont(f);
        g.drawString( tattoo, xpos + 60, ypos + 20 );
    }

}

class KeyListenerTester extends JFrame implements KeyListener {

        JLabel label;

        public KeyListenerTester() {
        }

        @Override
        public void keyTyped(KeyEvent e) {

            if (e.getKeyCode() == KeyEvent.VK_RIGHT) {

            }
            if (e.getKeyCode() == KeyEvent.VK_LEFT) {

            }

        }

        @Override
        public void keyPressed(KeyEvent e) {

            if (e.getKeyCode() == KeyEvent.VK_RIGHT) {

            }
            if (e.getKeyCode() == KeyEvent.VK_LEFT) {

            }

        }

        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_RIGHT) {

            }
            if (e.getKeyCode() == KeyEvent.VK_LEFT) {

            }
        }
    }

0 个答案:

没有答案