如何使用计时器在JPanel上移动分配给JLabel的图像?

时间:2019-01-16 22:54:37

标签: java image swing animation jlabel

我正在尝试创建侧面滚动游戏,其中背景图像不断向侧面移动,当到达终点时它将在起始位置重新开始。到目前为止,我已经能够将我的图像显示在屏幕上,但是我无法使用计时器来移动它。我已经尝试过使用for循环和repaint();,但是我不确定这是否是不断更新屏幕上图像位置的正确方法。

代码如下:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
 *
 * @author sam.k
 */
public class moving extends javax.swing.JFrame {
    private BufferedImage image;

    static int xPixel = 20;
    static int yPixel = 20; 
          BufferedImage myPicture = ImageIO.read(new File("H:\\Java\\picture\\src\\background.png"));

    JLabel picLabel = new JLabel(new ImageIcon(myPicture));

    /**
     * Creates new form moving
     */
    public moving() throws IOException {
         JFrame frame = new JFrame("main");
       frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

      this.setSize(1000, 700);

add(picLabel);
 Timer timer = new Timer(15, e -> {
            picLabel.repaint();
            moveImage();
        });
        timer.start();
    }

    class PaintSurface extends JComponent {

        public void paintComponent(Graphics g) {
            super.paintComponent(g);

        }

        /**
         * This method is called from within the constructor to initialize the
         * form. WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

}

 void moveImage() {

        for ( int i = 0 ; i < 500 ; i++ ){

           // System.out.println("next set of Pixels " + xPixel);

            xPixel +=1;
            yPixel +=1;
            repaint();

            // then sleep for a bit for your animation
            try { Thread.sleep(50); }   /* this will pause for 50 milliseconds */
            catch (InterruptedException e) { System.err.println("sleep exception"); }

        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(moving.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(moving.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(moving.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(moving.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new moving().setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(moving.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        });
    }

    // Variables declaration - do not modify                     
    // End of variables declaration                   
}

我认为在更新xPixel和yPixel之后重新粉刷会使其移动,但是它不起作用。感谢您的帮助。

0 个答案:

没有答案