我想從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
我不希望那個框架是空的。我想讓圖像反覆移動。每當背景圖片移動時,立即我想要下一張圖片被繪製,以便該框架看起來不會空白。 –