如何从keylistener方法中访问2d图形

时间:2018-01-10 13:54:29

标签: java swing awt keylistener graphics2d

您好我正在努力为高中游戏移动2d棒图,我有一个keylistener和方法,但我无法使用p1.translate根据他们按下的内容移动。我尝试使用循环/ if语句来检查使用变量(x)按下了什么按钮并根据它移动但是它也可以工作。所以基本上我试图从方法中访问p1(我的2d图形火柴人)来移动他。我尝试了副本中的那个,他们的修复不适合我。

import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JPanel;
import javax.swing.*;


public class game extends Frame{
    int x = 0;
    //used to call the frame I just created
    public static void main (String[] args)
    {
        new game();
    }

    //creates the frame
    public game(){
        super("2D World"); //output
        setSize(800,400);
        setVisible(true);

        //closes it when we hit X
        addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e)
            {dispose(); System.exit(0);}


        });}
        public void paint(Graphics p1){
            p1.setColor(Color.black);
            p1.drawOval(100, 200, 20, 20);
            p1.drawLine(110, 220, 110, 240);
            p1.drawLine(110, 240, 117, 260);
            p1.drawLine(110, 240, 100, 260);
            p1.drawLine(110, 220, 117, 240);
            p1.drawLine(110, 220, 100, 240);

    addKeyListener(new KeyAdapter() {

         public void keyPressed(KeyEvent evt) {
            switch(evt.getKeyCode()) {
               case KeyEvent.VK_LEFT:  moveLeft();  break;
               case KeyEvent.VK_RIGHT: moveRight(); break;
               case KeyEvent.VK_UP: moveUp(); break;
               case KeyEvent.VK_DOWN: moveDown(); break;

            }
         }
      });


    }
    protected void moveUp() {
        x = 1;

    }

    protected void moveRight() {
        x = 2;
    }

    protected void moveLeft() {
        x =3;
    }
    protected void moveDown() {
        x = 4;
    }

    /*class DrawCanvas extends JPanel{
        public void paint(Graphics p1){
            p1.setColor(Color.black);
            p1.drawOval(100, 200, 20, 20);
            p1.drawLine(110, 220, 110, 240);
            p1.drawLine(110, 240, 117, 260);
            p1.drawLine(110, 240, 100, 260);
            p1.drawLine(110, 220, 117, 240);
            p1.drawLine(110, 220, 100, 240);

        }
    }*/
    }

0 个答案:

没有答案