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);
}
}
Вот как он сначала нарисовал изображение, но позже он сказал, что для того, чтобы сделать его прокручиваемым, просто нужно добавить смещение x и offsety, где смещение - это то, насколько прокручивается карта. Я не был уверен в том, как определить их, поэтому я дал им целочисленное значение 300. Изображение теперь рисуется, но не реагирует на прокрутку. Я знаю, что мой код, вероятно, заставляет вас затыкать рот, но очень новый, поэтому, пожалуйста, потерпите меня на этом. Спасибо
Я считаю, что правильно выполнил шаги, но когда я пришел к последнему шагу, используя смещение, я был в замешательстве.