0

我似乎无法在 if 命令中更改纹理以进行按键操作。我有一种感觉,这更像是一个公共/私有变量的事情。

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class main extends JFrame {
public String w =("C:/users/John/workspace/Gamebasics/src/untitled.png");
int x, y, xDirection, yDirection;
private Image dbImage;
private Graphics dbg;
Image face;

int x1, y1;

public void move(){
    x += xDirection;
    y += yDirection;

}
public void setXDir(int xdir){
    xDirection = xdir;
}
public class AL extends KeyAdapter {
    public void keyPressed(KeyEvent e){
        int keyCode = e.getKeyCode();
        if(keyCode == e.VK_LEFT){
            w = ("C:/users/John/workspace/Gamebasics/src/left.png");
            if(x <= 5)
                x = 5;
            if(y >= 225 && y <=400 && x >= 225 && x <= 315)
                x = 315;
        x-= +4;
        }
        if(keyCode == e.VK_UP){
            w = ("C:/users/John/workspace/Gamebasics/src/up.png");
            if(y <= 28)
                y = 28;
            if(y >= 370 && y <=405 && x >= 225 && x <= 310)
                y = 405;
            y-= +4;
        }
        if(keyCode == e.VK_DOWN){
            w = ("C:/users/John/workspace/Gamebasics/src/down.png");
            if(y >= 470)
                y = 470;
            if(y <= 370 && y >=220 && x >= 225 && x <= 310)
                y = 220;
            y+= +4;
        }
        if(keyCode == e.VK_RIGHT){
            w = ("C:/users/John/workspace/Gamebasics/src/right.png");
            if(x >= 470)
                x = 470;
            if(y >= 225 && y <=400 && x >= 220 && x <= 315)
                x = 220;
            x+= +4;
        }
        }

}
public main(){
    ImageIcon i = new ImageIcon(w);
    face = i.getImage();
    addKeyListener(new AL());
    setTitle("Retarded Rectangle Game");
    setSize(500, 500);
    setResizable(false);
    setVisible(true);
    setBackground(Color.RED);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
    x = 340;
    y = 360;
    x1 = 250;
    y1 = 250;

}

public void paint(Graphics g){
    dbImage = createImage(getWidth(), getHeight());
    dbg = dbImage.getGraphics();
    paintComponent(dbg);
    g.drawImage(dbImage, 0, 0, this);
    g.setColor(Color.CYAN);
    g.fillRect(250, 250, 60, 150);
    repaint();
}


public void paintComponent (Graphics g){
    g.setColor(Color.CYAN);
    g.fillRect(250, 250, 60, 150);
    repaint();
    g.drawImage(face, x, y, this);
    repaint();
}

public static void main(String[] args){
    new main();
}
}
4

1 回答 1

0

您只是在更改变量“w”的值。您实际上并没有更改图像图标的值。重置“w”字符串后,您要么必须创建一个新的 ImageIcon,要么可能使用其中一种方法来更改资源位置。然后您可能还需要重新绘制框架。

于 2012-05-31T17:48:40.270 回答