我目前正在尝试将动画添加到具有各种对象在 2D 空间中移动和交互的程序中。我终于到了计时器工作的地方,程序让对象按照我想要的方式移动和交互......但它打开的显示面板仍然令人沮丧地空白。我一直在尝试使用网上找到的示例中的代码,但我仍然必须遗漏一些东西......
public class Populus2 extends JPanel
{
/**
* @param args
*/
static float[] xCoordinates;
static float[] yCoordinates;
static int duration;
static int iteration = 1;
static int graphSize = 500;
..............
static JFrame frame;
static JLabel lbl;
JPanel panel;
static Timer timer;
public static void main(String[] args) throws IOException {
final Populus2 pop = new Populus2();
frame = new JFrame("Animation Frame");
lbl = new JLabel();
Panel panel = new Panel();
panel.add(lbl);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(graphSize, graphSize);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener timeStep = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("at time " + iteration);
spendTime();
pop.repaint();
if(iteration>duration)
timer.stop();
}
};
timer = new Timer(100, timeStep);
timer.setInitialDelay(0);
timer.start();
}
@Override
public void paint(Graphics g)
{
super.paint(g);
System.out.println("******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n******PAINT******\n");
Graphics2D g2d = (Graphics2D) g;
paintCell(g, 1); //eventually, I want to call this method for every "cell" in the program
g.drawLine(30, 30, 80, 80); //this line's basically a test to see if I can display anything at all
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public void paintCell(Graphics graphics, int cellNumber)
{
graphics.setColor(Color.black);
graphics.fillOval((int)(graphSize*xCoordinates[cellNumber]/size), (int)(graphSize*yCoordinates[cellNumber]/size), 5, 5);
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < types.length; i++)
paintCell(g, i);
}
public static void spendTime()
{
//advances the iteration counter and recalculates the coordinates of all the cells
}
}
最终,我希望程序在计时器的每次迭代中为模拟中的每个单元调用paintCell(),每个单元代表一个移动对象。不过,目前,屏幕仍然是空白的。为了记录,我通过 System.out.println() 调用 paint() 的消息没有显示。想法?