【发布时间】:2013-12-25 08:39:50
【问题描述】:
我一直在做一项学校作业,老师希望我们在 JPanel 上出现 7 个圆圈并向下移动。一旦一个圆圈到达底部,就应该制作一个新圆圈来替换到达 JPanel 底部的圆圈。我决定使用一个数组来继续制作随机圆圈,但我无法让它正常工作。我使用了一个 for 循环来填充具有随机半径和颜色的圆的数组。代码可以编译,但是当我运行它时出现异常。我很难让阵列正常工作。我不确定的另一件事是如何绘制圆圈,以便它们在 JPanel 上留出空间。
代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.Random;
public class keyExample extends JPanel implements ActionListener, KeyListener {
private Circle[] circles = new Circle[7];
Timer t = new Timer(5, this);
//current x and y
double x = 150, y = 200;
double changeX = 0, changeY = 0;
private Circle;
private int circlex = 0, circley = 0; // makes initial starting point of circles 0
private javax.swing.Timer timer2;
public keyExample() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
timer2 = new javax.swing.Timer(33, new MoveListener());
timer2.start();
}
public void NewCircle() {
Random colors = new Random();
Color color = new Color(colors.nextInt(256), colors.nextInt(256), colors.nextInt(256));
Random num = new Random();
int radius = num.nextInt(45);
for (int i = 0; i < circles.length; i++) {
circles[i] = new Circle(circlex, circley, radius, color);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
g2.fill(new Rectangle2D.Double(x, y, 40, 40));
NewCircle();
for (int i = 0; i < circles.length; i++)
circles[i].fill(g);
}
public void actionPerformed(ActionEvent e) {
repaint();
x += changeX;
y += changeY;
changeX = 0;
changeY = 0;
}
public void up() {
if (y != 0) {
changeY = -3.5;
changeX = 0;
}
}
public void down() {
if (y <= 350) {
changeY = 3.5;
changeX = 0;
}
}
public void left() {
if (x >= 0) {
changeX = -3.5;
changeY = 0;
}
}
public void right() {
if (x <= 550) {
changeX = 3.5;
changeY = 0;
}
}
private class MoveListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
repaint();
Random speed = new Random();
int s = speed.nextInt(8);
circle.move(0, s);
}
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP) {
up();
}
if (code == KeyEvent.VK_DOWN) {
down();
}
if (code == KeyEvent.VK_RIGHT) {
right();
}
if (code == KeyEvent.VK_LEFT) {
left();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
【问题讨论】:
-
有什么异常?
-
我在代码上方添加了异常。它会继续打印出该异常,直到我关闭程序。
-
圆圈(您尝试在paintComponent中访问)为空
-
在你尝试用它作画之前让它非空。
标签: java swing jpanel keylistener paintcomponent