2 回答
TA贡献1876条经验 获得超5个赞
我解决了这个问题,并在此处发布了代码
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MainTest {
private final int TABLE_WIDTH = 300;
private final int TABLE_HEIGHT = 400;
private final int BALL_SIZE = 16;
private JFrame f = new JFrame("Pinball game");
Random rand = new Random();
private int ySpeed = 5;
private double xyRate = rand.nextDouble() - 0.5;
private int xSpeed = (int) (ySpeed * xyRate * 2);
private int ballX = rand.nextInt(200) + 20;
private int ballY = rand.nextInt(10) + 20;
private BackgroundPanel background = new BackgroundPanel();
Timer timer;
public void init() {
background.setBackground(new ImageIcon("res/cat1.jpg"));
background.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));
f.add(background);
ActionListener taskPerformer = evt -> {
if (ballX <= 0 || ballX >= TABLE_WIDTH - BALL_SIZE) {
xSpeed = -xSpeed;
} else if (ballY <= 0 || (ballY >= TABLE_HEIGHT - BALL_SIZE)) {
ySpeed = -ySpeed;
}
ballY += ySpeed;
ballX += xSpeed;
background.repaint();
};
timer = new Timer(10, taskPerformer);
timer.start();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
new MainTest().init();
}
public class BackgroundPanel extends JPanel {
private static final long serialVersionUID = 6702278957072713279L;
private Icon wallpaper;
public BackgroundPanel() {
}
protected void paintComponent(Graphics g) {
if (null != wallpaper) {
processBackground(g);
drawball(g);
}
System.out.println("f:paintComponent(Graphics g)");
}
public void setBackground(Icon wallpaper) {
this.wallpaper = wallpaper;
this.repaint();
}
private void processBackground(Graphics g) {
ImageIcon icon = (ImageIcon) wallpaper;
Image image = icon.getImage();
int cw = getWidth();
int ch = getHeight();
int iw = image.getWidth(this);
int ih = image.getHeight(this);
int x = 0;
int y = 0;
while (y <= ch) {
g.drawImage(image, x, y, this);
x += iw;
if (x >= cw) {
x = 0;
y += ih;
}
}
}
private void drawball(Graphics g){
g.setColor(Color.BLUE);
g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
}
}
}
添加回答
举报