首页 > 解决方案 > 在java中滚动背景图像不会移动

问题描述

    import java.awt.BorderLayout;
    import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;



 import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.Timer;

/*
 * 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.
 */

/**
 *
 * @author kids
 */
public class background extends javax.swing.JFrame {

    private PaintSurface canvas;
    private BufferedImage image;


    /**
     * Creates new form background
     */
    public background() {
         try {                
          image = ImageIO.read(new File("C:\\Users\\kids\\Documents\\NetBeansProjects\\game\\src\\backgroundimage.png"));
       } catch (IOException ex) {
            // handle exception...
       }
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Handle the CLOSE button
        pack();           // pack all the components in the JFrame
        setVisible(true); // show it
        requestFocus();   // set the focus to JFrame to receive KeyEvent

        super.setTitle("Game");
        this.setSize(1056, 540);
        this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
        this.add(new PaintSurface(), BorderLayout.CENTER);
        this.setVisible(true);
        canvas = new PaintSurface();
        this.add(canvas, BorderLayout.CENTER);


    }

    /**
     * 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>                        

    class PaintSurface extends JComponent {

        public void paint(Graphics g) {

            int width = image.getWidth();
int height = image.getHeight();
int mapWidth = 1056; //Get map width
int mapHeight = 540; //Get map height
int tilesx = 1056/width;
int tilesy = 540/height;
int offsetx = 300;
int offsety = 300;


            Graphics2D g2 = (Graphics2D) g;
            for(int y=0; y<tilesy; y++)
{
    for(int x=0; x<tilesx; x++)
    {
        g.drawImage(image, x*width-offsetx, y*height-offsety, null);

    }

        }
    }
    }
    /**
     *
     * @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(background.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(background.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(background.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(background.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() {
                new background();
            }
        });
    }

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

它绘制图像,但是当我滚动时它不会移动,所以我很困惑错误在哪里。我在各个地方寻找解释,最终我尝试了一个。

for(int y=0; y<tilesy; y++
{
    for(int x=0; x<tilesx; x++)
    {
        g.drawImage(myimage, x*width, y*height, null);
    }
}

这就是他最初绘制图像的方式,但他后来表示,为了使其滚动,只需添加一个 offsetx 和 offsety,其中的 offset 就是地图滚动了多少。我不确定如何定义这些,所以我给了它们一个整数值 300。现在正在绘制图像,但不响应任何类型的滚动。我知道我的代码可能会让你作呕,但非常新,所以请多多包涵。谢谢

我相信我正确地遵循了这些步骤,但是当我来到最后一步时,使用偏移量我很困惑。

标签: javaswing

解决方案


推荐阅读