无法移动图像

时间:2019-05-26 05:02:29

标签: graphics

我一直在尝试获取Jlabel,该Jlabel的图像可以通过箭头键移动,但事实并非如此。我将标签设置为图标,并在标签上添加了侦听器,但是即使这样,也不会设置新图像,标签也不会移动。我在做什么错了?

public class Main extends JPanel {
private Clip clip;
Character pro = new Protag();
private int protagX = pro.getX();
private int protagY = pro.getY();
JLabel protag; 
public static void main(String[] args) {
    JFrame mainFrame = new JFrame();
    Main main = new Main();
    mainFrame.add(main);


    mainFrame.setSize(1366,800);
    mainFrame.setLocation(90,10);
    mainFrame.setResizable(false);



    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setVisible(true);
    main.requestFocusInWindow();

}
public Main() {
    playMusic("battle.wav");
    this.setLayout(null);
//      Keyboard keyListener = new Keyboard(this);
//      this.addKeyListener(keyListener);
    ImageIcon proImage = pro.getImageIcon();
    //ImageIcon enemyImage = new ImageIcon(("yosuke-stance.gif"));
    protag = new JLabel();
    //JLabel enemy = new JLabel();
    protag.setIcon(proImage);

    //enemy.setIcon(enemyImage);
    add(protag);
    //add(enemy);
    Dimension size = protag.getPreferredSize();
    System.out.print(protagX);
    protag.setBounds(protagX,protagY,size.width,size.height);
    protag.addKeyListener(new KeyAdapter(){
        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub
            int code = e.getKeyCode();
            if (code == KeyEvent.VK_LEFT) {
                System.out.println("test");
                ImageIcon proImage = pro.getImageIcon();
                pro.setImageIcon(new ImageIcon("yu-walkback.gif"));
                protag.setIcon(proImage);
                protag.setLocation(protag.getX()-5,protag.getY());
                repaint();
            }
            else if (code == KeyEvent.VK_RIGHT) {  
                System.out.println("test");
                ImageIcon proImage = pro.getImageIcon();
                pro.setImageIcon(new ImageIcon("yu-walkback.gif"));
                protag.setIcon(proImage);
                protag.setLocation(protag.getX()+5,protag.getY());
                repaint();
            }
            else if (code == KeyEvent.VK_DOWN) {
                System.out.println("test"); 
            }
            else if (code == KeyEvent.VK_Z) {
                System.out.println("test"); 
                ImageIcon proImage = pro.getImageIcon();
                pro.setImageIcon(new ImageIcon("yu-spinslash.gif"));
                protag.setIcon(proImage);
                repaint();
            }

        }
    });


}

只要按箭头键图像就不会移动,我也不知道为什么

0 个答案:

没有答案