Для целей моего проекта я пытаюсь смоделировать шаблон филлотаксиса, создавая несколько кругов в реальном времени, используя приведенные формулы.
Так что недавно я решил попробовать программирование с помощью графического интерфейса вЯ использую JFrame и Swing, и я врезался в стену, пытаясь понять, как все работает правильно.Моя идея заключалась в том, чтобы медленно печатать окружность за кружком, вычисляя их координаты 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++;
}
}