我想从Java Swing制作简单的汽车游戏。我想要背景移动。当背景图片向下移动时,我不得不再次绘制它。 我该怎么做? PS:背景和background1是相同的图像如何重复绘制图像?
package com.mycompany.cardemo.car;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
*
* @author Suraj Gautam
*/
public class MainScreen extends JPanel implements ActionListener {
Timer timer = new Timer(20, this);
private ImageIcon background = new ImageIcon(getClass().getResource("/res/background.png"));
private ImageIcon background2 = new ImageIcon(getClass().getResource("/res/background1.png"));
private int x = 0;
private int y = 0;
private int velX = 1;
private int velY = 1;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
background.paintIcon(this, g, x, y);
if (y > 0 && y<400) {
background2.paintIcon(this, g, x, y);
}
timer.start();
}
public static void main(String[] args) {
JFrame f = new JFrame("Car game");
f.setSize(400, 400);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MainScreen());
f.setResizable(true);
f.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
y += velY;
repaint();
}
public void updateValueOfy(int y) {
this.y = y;
}
}
background2.paintIcon这里没有
我试过你的程序,background2.paintIcon适用于我。有一点需要注意的是,你的框架尺寸是400×400,当你> 0和Y <400时,你绘制背景2的条件是这样的。因此,在整个框架的可视区域中,background2将始终被绘制。在这里通过使background1和background2完全实现在这里试图达到什么目的? – Bon
我不希望那个框架是空的。我想让图像反复移动。每当背景图片移动时,立即我想要下一张图片被绘制,以便该框架看起来不会空白。 –