java - 如何在 JFrame 窗口中实时显示多个图像?
问题描述
出于我项目的目的,我试图通过使用给定的公式实时创建多个圆圈来模拟叶序模式。
所以最近,我决定尝试使用 JFrame 和 swing 在 Java 中进行 GUI 编程,但我在试图弄清楚如何让一切正常运行时遇到了困难。我的想法是慢慢地打印出一个又一个圆圈,它们的 x 和 y 坐标是根据叶序指令中记录的“r = cos/sin(theta)”公式计算的。不幸的是,虽然 x 和 y 值不断变化,但只打印了一个圆圈。有什么我想念的吗?
package gExample;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
public class GraphicsExample extends Canvas implements ActionListener {
private final static int HEIGHT = 600;
private final static int WIDTH = 600;
private int n = 0;
private int x, y;
Timer t = new Timer(20, this);
public static void main(String args[]) {
JFrame frame = new JFrame();
GraphicsExample canvas = new GraphicsExample();
canvas.setSize(WIDTH, HEIGHT);
frame.add(canvas);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas.setBackground(Color.black);
}
public void paint(Graphics g){
Random rand = new Random();
Color col = new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
g.setColor(col);
/*each time paint() is called, I expect a new circle to be printed in the
x and y position that was updated by actionPerformed(), but only one inital circle is created. */
g.fillOval(x, y, 8, 8);
t.start();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int c = 9;
double r = c * Math.sqrt(n);
double angle = n * 137.5;
//here, every time the method is called, the x and y values are updated,
//which will be used to fill in a new circle
int x = (int) (r * Math.cos(angle * (Math.PI / 180) )) + (WIDTH / 2);
int y = (int) (r * Math.sin(angle * (Math.PI / 180) )) + (HEIGHT / 2);
//when the program is running, this line of code is executed multiple times.
System.out.println("x: " + x + " y: " + y);
n++;
}
}
解决方案
推荐阅读
- django - 测试表单字段小部件类型
- ios - iOS web 视图删除历史记录
- azure-eventgrid - 无法在 azure 门户中查看 eventgrid 订阅。也无法创建新的
- node.js - 反应 NodeJS 开发工作流程
- wordpress - Wordpress Bootstrap Navwalker 让我发疯
- sql-server - 使用 sql 查询或 sp 在存储过程中查找特定的 ResultSet
- javascript - Javascript:如何从输出中选择特定部分
- c# - 可以从 UI 线程的任务中调用 Thread.Sleep(n) 冻结 UI 吗?
- python - 安装包时 Pip 给出同样的错误
- angular - 错误:初始化错误(打字稿)。无法读取未定义的属性“getExecutingFilePath”