В основном я пытаюсь нарисовать спираль, взяв массивы из 4 точек, по одному в каждом углу кадра, и заставить их следовать друг за другом в направлении против часовой стрелки, пока они не достигнут центра. Точки движутся вперед по прямой линии, но их координаты x и y изменяются пропорционально расстоянию между ними на каждом временном шаге.
Попытка выяснить, как сохранить массивы в пределах экрана. Ничего не появляется.
Пожалуйста, дайте мне знать, если у вас есть идея, куда идти отсюда. Вся помощь приветствуется. Вот что у меня есть до сих пор:
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.util.*;
import java.io.*;
public class Slugs extends JPanel {
private static final long serialVersionUID = 1L;
//Lines update for 1000 ticks
final int max = 1000;
//Initial seed
public int i = 0;
//Translates each point into an array value
final double[][][] points = new double[4][2][];
@SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException {
//Creates scanner object for file output name
Scanner console = new Scanner(new File("slug_details.txt"));
//Creates scanner object for edge and node values
String edge = console.nextLine();
Scanner console1 = new Scanner(edge);
//Scans input file for all values
@SuppressWarnings("unused")
String file = console1.next();
int width = console1.nextInt();
int d = console1.nextInt();
//Creates frame
JFrame frame = new JFrame();
//Sets frame size
frame.setSize(width, width);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Slugs panel = new Slugs(frame.getWidth(), d);
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.setResizable(false);
}
public Slugs(final int width, int d) {
//Sets up the array
for (int edge = 0; edge < points.length; edge++) {
for (int node = 0; node < points[edge].length; node++) {
points[edge][node] = new double[max];
}
}
//Top-left corner
points[0][0][0] = 0;
points[0][1][0] = 0;
//Bottom-left corner
points[1][0][0] = 0;
points[1][1][0] = width;
//Bottom-right corner
points[2][0][0] = width;
points[2][1][0] = width;
//Top-right corner
points[3][0][0] = width;
points[3][1][0] = 0;
for (int i = 1; i < max; i++) {
for (int edge = 0; edge < points.length; edge++) {
//Updates subsequent vector positions
final double vectX = points[(edge + 1) % 4][0][i - 1]
- points[edge][0][i - 1];
final double vectY = points[(edge + 1) % 4][1][i - 1]
- points[edge][1][i - 1];
//Get vector length
final double length = hypot(vectX, vectY);
//Constrain vector length by screen bounds
final double deltaX = vectX;
final double deltaY = vectY;
//Save current point
points[edge][0][i] = points[edge][0][i - 1] + deltaX;
points[edge][1][i] = points[edge][1][i - 1] + deltaY;
}
}
}
//Draws the algorithm
public void paintComponent(Graphics g) {
if (i < max - 1) {
g.setColor(Color.blue);
for (int edge = 0; edge < points.length; edge++) {
g.drawLine((int) points[edge][0][i], (int) points[edge][1][i], (int) points[edge][0][i + 1], (int) points[edge][1][i + 1]);
}
i++;
repaint();
}
}
}
//Formula for the distance between two points
static double hypot(double a, double b) {
return Math.sqrt(a * a + b * b);
}
2 ответа
Вот то, что вы ищете ... хороший взгляд на объяснение вашему профессору, что вы поняли это самостоятельно, но, как бы то ни было, создание красивого спирального узора было забавным.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Spiral extends JPanel implements Runnable {
public static final int WIDTH = 500;
public static final double PIX_RES = 3;
public static final double WEIGHT = PIX_RES / WIDTH;
public static final long SLEEP_TIME = 10;
private final GeneralPath topRight = new GeneralPath();
private final GeneralPath topLeft = new GeneralPath();
private final GeneralPath bottomLeft = new GeneralPath();
private final GeneralPath bottomRight = new GeneralPath();
public Spiral(){
this(WIDTH);
}
public Spiral(final int width) {
super();
this.setPreferredSize(new Dimension(width, width));
topRight.moveTo(width, 0);
topLeft.moveTo(0, 0);
bottomLeft.moveTo(0, width);
bottomRight.moveTo(width, width);
}
@Override
public void paintComponent(final Graphics g) {
final Graphics2D g2 = (Graphics2D) g;
g2.draw(topLeft);
g2.draw(topRight);
g2.draw(bottomLeft);
g2.draw(bottomRight);
}
/**
* generated by eclipse
*/
private static final long serialVersionUID = -756842929825603438L;
@Override
public void run() {
while (true) {
iterate();
this.repaint();
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void iterate() {
final double dx = topRight.getCurrentPoint().getX()
- topLeft.getCurrentPoint().getX();
final double dy = -topRight.getCurrentPoint().getY()
+ topLeft.getCurrentPoint().getY();
final Point2D pTR = topRight.getCurrentPoint();
final Point2D pTL = topLeft.getCurrentPoint();
final Point2D pBL = bottomLeft.getCurrentPoint();
final Point2D pBR = bottomRight.getCurrentPoint();
topRight.lineTo(pTR.getX() - dx * WEIGHT, pTR.getY() + dy * WEIGHT);
topLeft.lineTo(pTL.getX() + dy * WEIGHT, pTL.getY() + dx * WEIGHT);
bottomRight.lineTo(pBR.getX() - dy * WEIGHT, pBR.getY() - dx * WEIGHT);
bottomLeft.lineTo(pBL.getX() + dx * WEIGHT, pBL.getY() - dy * WEIGHT);
}
public static void main(String... args) {
final JFrame frame = new JFrame("spiral");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// who cares
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Spiral spiral = new Spiral();
frame.setContentPane(spiral);
frame.pack();
frame.setVisible(true);
(new Thread(spiral)).start();
}
}
Этот эффект называется «кривой преследования». Я изменил вашу программу, чтобы продемонстрировать эффект.
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JFrame;
public class Slugs extends JPanel {
private static final long serialVersionUID = 1L;
// Max length of line segment.
final double range = 1;
// Total number of iterations of the algorithm.
final int num = 2000;
// current iteration
public int i = 0;
// Declare arrays for points.
final double[][][] points = new double[4][2][];
public Slugs (final int width, final int height) {
// initialize arrays for points.
for (int line = 0; line < points.length; line++)
{
for (int axis = 0; axis < points[line].length; axis++)
{
points[line][axis] = new double[num];
}
}
// First point placed in center of panel.
points[0][0][0] = 100;
points[0][1][0] = 100;
points[1][0][0] = 100;
points[1][1][0] = 700;
points[2][0][0] = 700;
points[2][1][0] = 700;
points[3][0][0] = 700;
points[3][1][0] = 100;
// Generate a random point.
for (int i = 1; i < num; i++)
{
// for each line
for (int line = 0; line < points.length; line++) {
// calculate vector from last point on this line to last point
// on the line we're chasing
final double vectX =
points[(line + 1) % 4][0][i - 1] - points[line][0][i - 1];
final double vectY =
points[(line + 1) % 4][1][i - 1] - points[line][1][i - 1];
// find length of the vector
final double length = hypot(vectX, vectY);
// adjust vector length to max allowable range
final double deltaX = vectX / length * range;
final double deltaY = vectY / length * range;
// record current point
points[line][0][i] = points[line][0][i - 1] + deltaX;
points[line][1][i] = points[line][1][i - 1] + deltaY;
}
}
}
public void paintComponent(Graphics g) {
if(i < num - 1) {
g.setColor(Color.blue);
for (int line = 0; line < points.length; line++)
{
g.drawLine(
(int) points[line][0][i], (int) points[line][1][i],
(int) points[line][0][i + 1], (int) points[line][1][i + 1]);
}
i++;
delay(0);
// sketchy recursion. If num is too high the program will crash
repaint();
}
}
public static void main(String[] args) {
// Generates frame.
JFrame frame = new JFrame();
// Sets frame resolution and other frame parameters.
frame.setSize(800, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Slugs panel = new Slugs(frame.getWidth(), frame.getHeight());
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.setResizable(false);
}
//Defines speed of delay between ticks.
public static void delay(long milliseconds) {
try {
Thread.sleep(milliseconds);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
// hypotenuse length
static double hypot(double a, double b)
{
return Math.sqrt(a * a + b * b);
}
}
Похожие вопросы
Новые вопросы
java
Java — это высокоуровневый объектно-ориентированный язык программирования. Используйте этот тег, если у вас возникли проблемы с использованием или пониманием самого языка. Этот тег часто используется вместе с другими тегами для библиотек и/или фреймворков, используемых разработчиками Java.