通过不同的按键切换纹理

时间:2012-05-31 17:25:43

标签: java

我似乎无法在按键的if-command中更改纹理。我觉得这更像是一个公共/私人变量。

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();
}
}

1 个答案:

答案 0 :(得分:0)

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