2012-05-31 14 views
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(); 
} 
} 
+0

我看不到有關更改紋理的代碼 – ControlAltDel

+0

在JFrame中重寫paintComponent不會執行任何操作。您需要創建一個JPanel並將其添加到contentPane或將其設置爲contentPane – ControlAltDel

回答

0

你只是在改變變量'w'的值。你實際上並沒有改變圖像圖標的值。重置'w'字符串後,您必須創建一個新的ImageIcon,或者可以使用其中一種方法來更改資源位置。然後,您可能還必須重新繪製框架。