java - 这个错误出现在我的java程序中,似乎没有任何原因

标签 java image sprite

出于某种原因,当我的 Sprite 碰到左侧边缘时,它不会反弹。该程序运行得很好,但后来我更改了一些实际上根本不应该对其产生任何影响的内容,然后它就停止运行了。

//Sprite class

public class Sprite {
private String sprite = "sprite-adult.fw.png";

private int speed;
private int dx;
private int dy;
private int x;
private int y;
private Image image;

public Sprite() {
    ImageIcon ii = new ImageIcon(getClass().getResource(sprite));
    image = ii.getImage();

            speed=6;
            dx=speed;
            dy=speed;

    x = 40;
    y = 60;
}
public void move() {
    toggleRebound();

    x += dx;
    y += dy;
}
public void toggleRebound() {
    if(x == 1366) 
        dx = negate(dx);

    if(y == 768) 
        dy = negate(dy);

    if(x == 0) 
        dx = negate(dx);

    if(y == 0) 
        dy = negate(dy);    
}
public int negate(int x) {
    return x*-1;
}
public int getX() {
    return x;
}
public int getY() {
    return y;
}
public Image getImage() {
    return image;
}
}


//SType class

public class SType extends JFrame{
public SType() {
    add(new Board());

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(1366,768);
    setLocationRelativeTo(null);
    setTitle("S - Type");
    setVisible(true);
    setResizable(false);
}
public static void main(String[] args) {
    new SType();
}
}

//Board class

public class Board extends JPanel implements ActionListener{
private Sprite sprite;
private Timer timer;

public Board() {
    setFocusable(true);
    setBackground(new Color(39,124,36));
    setDoubleBuffered(true);

    sprite = new Sprite();

    timer = new Timer(5,this);
    timer.start();
}
public void paint(Graphics g) {
    super.paint(g);

    Random rand = new Random(5398);
    for(int x=0;x<1000;x++) {
        g.setColor(new Color(22,98,19));
        g.drawOval(rand.nextInt(1368), rand.nextInt(768), 1, 20);
    }

    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(sprite.getImage(),sprite.getX(),sprite.getY(),this);

    Toolkit.getDefaultToolkit().sync();
}
public void actionPerformed(ActionEvent arg0) {
    sprite.move();
    repaint();
}
}

最佳答案

第一个回答者是正确的,这不应该影响任何事情。尽管在本例中它并不真正相关,但在构造函数中初始化私有(private)实例变量而不是使用它们的声明是一种很好的形式。

private int speed;
private int dx;
private int dy;

public Sprite()
{
    speed=6;
    dx=speed;
    dy=speed;
}

关于java - 这个错误出现在我的java程序中,似乎没有任何原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602748/

相关文章:

使用 Gabor 滤波器的图像纹理特征

c++ - 如何在不破坏其纹理的情况下将 Sprite 正确传递给 std::Vector?

java - 如何在 Ubuntu 上使用 Eclipse (Luna) 设置 Hibernate

java - Mapbox:位置符号(圆盘)显示在路线下方

java - 如何用javapoet生成类参数?

Android 将图像保存到外部存储,但 ContentResolver.insert 始终返回 null

java - 防止尝试下载视频服务器中的视频

ios - 如何在 TableView 中为不同的索引显示不同的图像?

cocos2d-iphone - 如何创建一个 CCSprite 来设置边界?

c++ - 在 cocos2d-x 中切换 Sprite 动画