【发布时间】:2014-06-02 15:11:43
【问题描述】:
已尝试搜索,但找不到任何内容。
我正在尝试使用一个数组和一个 for 循环绘制多个 2D 椭圆,我每秒都在重新绘制帧。问题是,我每次重画时只得到一个 Ellipse,有人可以告诉我代码有什么问题吗?
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class MovingDot extends JFrame{
static int posX = (int)Math.round(Math.random()*780);
static int posY = (int)Math.round(Math.random()*780);
static int width = (int)Math.round(Math.random()*780);
static int height = (int)Math.round(Math.random()*780);
static int dots = 0;
public static Timer timer;
public MovingDot(){
super("Moving Dot");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(800, 800);
Dot2 dot = new Dot2();
add(dot);
setVisible(true);
timer = new Timer((int)Math.round((1000)), timerAction);
timer.start();
}
private ActionListener timerAction = new ActionListener(){
@Override
public void actionPerformed(ActionEvent ae){
posX = (int)Math.round(Math.random()*780);
posY = (int)Math.round(Math.random()*780);
width = (int)Math.round(Math.random()*780);
height = (int)Math.round(Math.random()*780);
float r = (float)Math.random();
float g = (float)Math.random();
float b = (float)Math.random();
Color col = new Color(r,g,b);
setBackground(col);
dots++;
repaint();
}
};
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run()
{
new MovingDot();
}
});
}
}
class Dot2 extends JPanel{
@Override
public void paintComponent(Graphics c2){
int x = MovingDot.posX;
int y = MovingDot.posY;
int w = MovingDot.width;
int h = MovingDot.height;
float r,g,b;
Color col;
Graphics2D c = (Graphics2D) c2;
c.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Ellipse2D.Float[] e = new Ellipse2D.Float[10];
for (int i = 0; i < 10; i++) {
if (i == 0)
r = (float)Math.random();
else
r = 0.163F;
g = (float)Math.random();
b = (float)Math.random();
col = new Color(r,g,b);
c.setColor(col);
e[i] = new Ellipse2D.Float(x, y, w, h);
c.fill(e[i]);
}
}
}
我自己发现了问题所在,我不得不在我的paintComponent 中使x、y、w 和h 随机化。不,这不是学校作业,我正在尝试用一本书自学 Java。
关于使我的方法静态化,我计划在我的 JPanel 中使用它们,但我意识到我不需要它们,所以我将删除它们。谢谢你的建议!
【问题讨论】:
标签: java swing awt graphics2d ellipse