簡體   English   中英

通過不同的按鍵切換紋理

[英]Switching Textures by different keypresses

我似乎無法在按鍵的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();
}
}

您僅更改變量“ w”的值。 您實際上並沒有更改圖像圖標的值。 重置'w'字符串后,您要么必須創建一個新的ImageIcon,要么使用其中一種方法來更改資源位置。 然后,您可能還需要重新粉刷框架。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM