Java图形没有从播放器类中绘制getX()和getY()

时间:2014-08-15 20:50:38

标签: java swing

嗯,我说的不多,但基本上我有一个Player课程,然后在GFX课程中,我正在用他的Player和{{getX()绘制getY() 1}}所以player.getX()

所以你可以看到我制作了getter和setter但是现在它不会在GFX中绘制它只会给我错误。

    package com.shiny21.players;

public class PlayerR {

    int x = 10;
    int y = 10;

    public PlayerR(int x, int y){
        this.x = x;
        this.y = y;
        setX(10);
        setY(10);

    }

    public void init(){

    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }



}

package com.shiny21.graphics;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.Timer;

import com.shiny21.players.PlayerR;

public class GFX extends JPanel implements ActionListener{

    PlayerR red;

    public GFX(){

        PlayerR red = new PlayerR(getX(), getY());

        this.setFocusable(true);
        this.requestFocus();

        setBackground(Color.BLACK);

        Timer timer = new Timer(1000 / 60, this);
        timer.start();
    }

    public void step(){
        System.out.println(":p");
        repaint();
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);

        g.setColor(Color.BLUE);
        g.fillRect(50, 50, 4, 4);

        g.setColor(Color.RED);
        g.fillRect(red.getX(), red.getY(), 4, 4);


    }


    public void actionPerformed(ActionEvent ae) {
        step();
    }
}

1 个答案:

答案 0 :(得分:1)

发布错误日志后,我会编辑答案。现在我要指出一两件事:


public PlayerR(int x, int y){
    this.x = x;
    this.y = y;
    setX(10);
    setY(10);

}

为什么直接分配变量然后使用它的各自的setter方法?它应该只是:

public PlayerR(int x, int y){
    this.x = x;
    this.y = y;
}

此外:

 PlayerR red = new PlayerR(getX(), getY());

应为red = new PlayerR(getX(), getY());

由于PlayerR red;已全局声明。