【发布时间】:2018-05-07 19:05:09
【问题描述】:
我正在尝试使用多线程制作动画。我想在 n 来自推荐行参数的地方绘制 n 个方块。每个方块都有它们的 x-y 坐标、颜色和速度。它们以不同的速度、颜色和坐标移动到画面的右侧。由于我使用的是多线程,我假设我必须控制每个方块。所以我必须将每个方形对象存储在 ArrayList 中。但是,我在绘制这些正方形时遇到了麻烦。我可以画一个正方形,但是当我尝试画多个正方形时,它不显示。这是我到目前为止所做的:
DrawSquare.java
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawSquare extends JPanel {
public Square square;
public DrawSquare() {
square = new Square();
}
@Override
public void paintComponents(Graphics g) {
// TODO Auto-generated method stub
super.paintComponents(g);
}
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.setColor(square.getC());
g.fillRect(square.getX(), square.getY(), square.getR(), square.getR());
}
}
Square.java
import java.awt.Color;
import java.util.Random;
public class Square {
private int x,y,r,s;
private Color c;
private Random random;
public Square() {
random = new Random();
x = random.nextInt(100) + 30;
y = random.nextInt(100) + 30;
r = random.nextInt(50) + 20;
s = random.nextInt(20) + 5;
c = new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getR() {
return r;
}
public int getS() {
return s;
}
public Color getC() {
return c;
}
}
Animation.java
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Animation extends JFrame implements Runnable {
private JPanel panel;
private DrawSquare square;
public Animation() {
}
public static void main(String[] args) {
Animation w = new Animation();
DrawSquare square = new DrawSquare();
JFrame f = new JFrame("Week 9");
int n = Integer.parseInt(args[0]);
f.setVisible(true);
f.setSize(700,700);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
for(int i=0; i<n; i++) {
f.getContentPane().add(square);
}
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
【问题讨论】:
-
So I have to store each square object in the ArrayList.- 很好。However, I am having trouble with painting those squares. I can paint one square but when I try to paint multiple squares, it does not show- 您需要遍历 ArrayList 来绘制每个正方形。因此,您需要一个面板来绘制所有正方形,而不是让多个面板分别绘制一个正方形。查看:stackoverflow.com/questions/42358359/… 获取工作示例。
标签: java multithreading swing animation paint