Image moving to the target - java

A and C images are far away.
At this time, B image is created from the coordinate values ​​of A
For each iteration, x, y must be moved to arrive at the C image coordinate value.
For example,
A (100,100), C (300,300)
Starting at B (100,100),
Each time it is repeated, x, y must be moved to reach
B (300,300).
This is the method for entering the current moving source.
Public void Attack () {
int x1 = a.getX ();
int y1 = a.getY ();
int x2 = c.getX ();
int y2 = c.getY ();
if(b.getX ()==c.getX&&b.getY () == c.getY())'
{
system.out.println ("ok");'
}else {
b.setbounds (help1,help2,100,50)
}
}
Here, I want to know the code to enter help1 help2.
Pythagorean formula
Between A and C images
I want to know how to make the B image move along a virtual straight line.
Like a tower defense game.
A image is a tower
B image is bullet
The C image is the enemy.
I want the bullets fired from the tower to move to enemy locations.
I am Korean.
I used a translator

The following code is an mre of using a straight line equation y = mx + c to draw a moving object along such line.
To test the code copy the entire code into MoveAlongStraightLine.java and run, or run it online:
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class MoveAlongStraightLine extends JFrame {
public MoveAlongStraightLine(){
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
ShootinBoard shootingBoard = new ShootinBoard();
JButton fire = new JButton("Fire");
fire.addActionListener(e->shootingBoard.fire());
add(shootingBoard);
add(fire, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public static void main(String[]args){
SwingUtilities.invokeLater(()->new MoveAlongStraightLine());
}
}
class ShootinBoard extends JPanel{
//use constants for better readability
private static final double W = 600, H = 400;
private static final int DOT_SIZE = 10, SPEED = 2;
private final int dX = 1; //x increment
private final Timer timer;
private final Point2D.Double shooter, target;
private Point2D.Double bullet;
public ShootinBoard() {
setPreferredSize(new Dimension((int)W, (int)H));
shooter = new Point2D.Double(50,350);
bullet = shooter; //place bullet at start point
target = new Point2D.Double(550,50);
timer = new Timer(SPEED, e->moveBullet());
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setStroke(new BasicStroke(3));
//draw source
g2.setColor(Color.blue);
g2.draw(new Ellipse2D.Double(shooter.getX(), shooter.getY(),DOT_SIZE , DOT_SIZE));
//draw bullet
g2.setColor(Color.black);
g2.draw(new Ellipse2D.Double(bullet.getX(), bullet.getY(),DOT_SIZE , DOT_SIZE));
//draw target
g2.setColor(Color.red);
g2.draw(new Ellipse2D.Double(target.getX(), target.getY(),DOT_SIZE , DOT_SIZE));
}
void fire(){
timer.stop();
bullet = shooter; //place bullet at start point
timer.start();
}
void moveBullet() {
if(target.x == bullet.x && target.y == bullet.y) {
timer.stop();
}
//y = mx + c for more details see https://www.usingmaths.com/senior_secondary/java/straightline.php
double m = (target.y - bullet.y)/ (target.x - bullet.x);//slope
double c = (target.x * bullet.y - bullet.x * target.y)/(target.x - bullet.x);
double newBulletX = bullet.x+dX; //increment x
double newBulletY = m * newBulletX + c; //calculate new y
bullet = new Point2D.Double(newBulletX,newBulletY);
repaint();
}
}

Related

How do you display more than one image in the JFrame window in real time?

For the purposes of my project, I'm trying to simulate a phyllotaxis pattern by creating multiple circles in real time using the formulas given.
So recently, I've decided to try out GUI programming in Java using JFrame and swing, and I've hit a wall trying to figure out how to get everything running properly. My idea was to slowly print out circle after circle with their x and y coordinates being calculated from the "r = cos/sin(theta)" formulas documented in the phyllotaxis instructions. Unfortunately, while the x and y values are constantly changing, only one circle is printed. Is there something I am missing?
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++;
}
}

Draw random dots inside a circle

I would like to draw 50 random dots within a given circle. The problem is the dots are not contained in the circle. Here is a runnable example:
package mygraphicsshapehomework;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
public class MyGraphicsShapeHomeWork extends JFrame {
public static void main(String[] args) {
new MyGraphicsShapeHomeWork();
}
public MyGraphicsShapeHomeWork() {
super("Title");
setBounds(600, 400, 700, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawOval(40, 40, 90, 90);
Color newColor = new Color(255, 0, 0);
g2.setColor(newColor);
for (int i = 0; i < 50; i++) {
int x = (int) Math.ceil(Math.random() * 10);
int y = (int) Math.ceil(Math.random() * 10);
g2.fillOval(i+x, i+y, 3, 3); // ???
}
}
}
Here is the result it produces:
How can I draw the dots within the circle only?
To get a random point in a circle with radius R find a random angle and a random radius:
double a = random() * 2 * PI;
double r = R * sqrt(random());
Then the coordinates of the point are:
double x = r * cos(a)
double y = r * sin(a)
Here are some notes about the drawing part. You should not paint directly on top level container such as JFrame. Instead, use JComponent or JPanel. Override paintComponent() for painting rather than paint() and don't forget to call super.paintComponent(g)
Take a look at Performing Custom Painting tutorial for more information.
Do not use setBounds(), override panel's getPreferredSize() and pack() the frame. Also, you rarely need to extend JFrame.
Here is a basic example that demonstrates drawing with a sub-pixel precision:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestDots extends JPanel{
public static final int POINTS_NUM = 1000;
public static final Color POINT_COLOR = Color.RED;
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
double padding = 10;
double radius = Math.min(this.getWidth(), this.getHeight()) / 2 - padding * 2;
g2.draw(new Ellipse2D.Double(padding, padding, radius * 2, radius * 2));
g2.setColor(POINT_COLOR);
for (int i = 0; i < POINTS_NUM; i++) {
double a = Math.random() * 2 * Math.PI;
double r = radius * Math.sqrt(Math.random());
double x = r * Math.cos(a) + radius + padding;
double y = r * Math.sin(a) + radius + padding;
g2.draw(new Ellipse2D.Double(x, y, 1, 1));
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("TestDots");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.add(new TestDots());
frame.pack();
frame.setVisible(true);
}
});
}
}
Here is a result:
For the position of the dots, generate random coordinates within the bounds of the outer circle. In order to generate these coordinates, the radius of the point from the center of the circle must be less than that of the outer circle. Get a random angle using
float a = Math.random() * Math.PI * 2;
Then, subtract a random value from the outer radius:
outerR - (Math.sqrt(Math.random()) * outerR)
and assign the positions to:
double x = Math.cos(a)*newR;
double y = Math.sin(a)*newR;
I'm sure there is a more mathematical approach to this, but this was the simplest in my opinion.

Java - Calculating and placing the angle of a geometric shape

I'm currently working on a program which enables user to draw various geometric shapes. However, I got some issues on calculating and placing the angle objects onto my Canvas panel accurately. The angle object is basically an extension of the Arc2D object, which provides a additional method called computeStartAndExtent(). Inside my Angle class, this method computes and finds the necessary starting and extension angle values:
private void computeStartAndExtent()
{
double ang1 = Math.toDegrees(Math.atan2(b1.getY2() - b1.getY1(), b1.getX2() - b1.getX1()));
double ang2 = Math.toDegrees(Math.atan2(b2.getY2() - b2.getY1(), b2.getX2() - b2.getX1()));
if(ang2 < ang1)
{
start = Math.abs(180 - ang2);
extent = ang1 - ang2;
}
else
{
start = Math.abs(180 - ang1);
extent = ang2 - ang1;
}
start -= extent;
}
It is a bit buggy code that only works when I connect two lines to each other, however, when I connect a third one to make a triangle, the result is like the following,
As you see the ADB angle is the only one that is placed correctly. I couldn't figure how to overcome this. If you need some additional info/code please let me know.
EDIT: b1 and b2 are Line2D objects in computeStartAndExtent() method.
Thank you.
There are some of things that can be made to simplify the calculation:
Keep the vertices ordered, so that it is always clear how to calculate the vertex angles pointing away from the corner
Furthermore, always draw the polygon to the same direction; then you can always draw the angles to the same direction. The example below assumes the polygon is drawn clockwise. The same angle calculation would result in the arcs drawn outside given a polygon drawn counterclockwise.
Example code; is not quite the same as yours as I don't have your code, but has similar functionality:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Arc2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Polygon extends JPanel {
private static final int RADIUS = 20;
private final int[] xpoints = {
10, 150, 80, 60
};
private final int[] ypoints = {
10, 10, 150, 60
};
final Arc2D[] arcs;
Polygon() {
arcs = new Arc2D[xpoints.length];
for (int i = 0; i < arcs.length; i++) {
// Indices of previous and next corners
int prev = (i + arcs.length - 1) % arcs.length;
int next = (i + arcs.length + 1) % arcs.length;
// angles of sides, pointing outwards from the corner
double ang1 = Math.toDegrees(Math.atan2(-(ypoints[prev] - ypoints[i]), xpoints[prev] - xpoints[i]));
double ang2 = Math.toDegrees(Math.atan2(-(ypoints[next] - ypoints[i]), xpoints[next] - xpoints[i]));
int start = (int) ang1;
int extent = (int) (ang2 - ang1);
// always draw to positive direction, limit the angle <= 360
extent = (extent + 360) % 360;
arcs[i] = new Arc2D.Float(xpoints[i] - RADIUS, ypoints[i] - RADIUS, 2 * RADIUS, 2 * RADIUS, start, extent, Arc2D.OPEN);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(160, 160);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawPolygon(xpoints, ypoints, xpoints.length);
Graphics2D g2d = (Graphics2D) g;
for (Shape s : arcs) {
g2d.draw(s);
}
}
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Polygon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Polygon());
frame.pack();
frame.setVisible(true);
}
});
}
}
Results in:

How to make a JButton move along with drawn lines

I have Jbutton (represented by the envelope) and an ArrayList of lines which the Envelope will go along. Can anyone help me? any ideas or tutorial will be much appreciated.
I assume that your goal is to animate the envelope along the line to provide an animation of data being transferred.
For every line you need first to find the line equation. A line equation is in the form y = a * x + b. If you already have that in the List you mention then that's fine. If on the other hand you have two points instead (start and end positions), use those with the above equation to find a, b for each line.
After you have the equations for your lines then you can use an animation (probably with a SwingWorker or a SwingTimer) that would increase the x coordinate of your envelope at regular intervals and then use the line equation to calculate the new y coordinate.
I hope that helps
Update: Added code snippet for a moving box using a SwingTimer for demonstration
package keymovement;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
public class TestMovingObject {
static class Envelope {
double x;
double y;
void setPosition(double x, double y) {
this.x = x;
this.y = y;
}
}
static class DrawArea extends JPanel {
Envelope envelope = new Envelope();
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
int x = (int) Math.round(envelope.x);
int y = (int) Math.round(envelope.y);
g.drawRect(x, y, 20, 20);
}
public Envelope getEnvelope() {
return envelope;
}
}
/**
* #param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
throw new RuntimeException(e);
}
JFrame window = new JFrame("Moving box");
window.setPreferredSize(new Dimension(500, 400));
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final DrawArea mainArea = new DrawArea();
window.add(mainArea);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
int delay = 20; // execute every 20 milliseconds i.e. 50 times per second
Timer timer = new Timer(delay, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Envelope envelope = mainArea.getEnvelope();
double x = envelope.x + 1; // use smaller increments depending on the desired speed
double y = 0.5 * x + 2; // moving along the line y = 0.5 * x + 2
envelope.setPosition(x, y);
mainArea.repaint();
}
});
timer.setRepeats(true);
timer.start();
}
});
}
}
Can you tell me a very simple example?
In this game, enemies advance toward the player one row or column at time, without calculating any intermediate points. When the destination is stationary, the path is a straight line. The animation is paced by a javax.swing.Timer. See RCModel#move() and RCView#timer for the implementation.
There are some mathematic things to do for you.
Check out this article: http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
This simple algorithm will tell you each X,Y coordinate on a line between two points. You could use this algorithm to compute all of the positions it needs to visit, store the coordinates in an array, and iterate over the array as you update the position.
There is an alternative helper class:
package snippet;
import java.awt.geom.Point2D;
public class MyVelocityCalculator {
public static void main(String[] args) {
Point2D.Double currentPosition = new Point2D.Double();
Point2D.Double destinationPosition = new Point2D.Double();
currentPosition.setLocation(100, 100);
destinationPosition.setLocation(50, 50);
Double speed = 0.5;
System.out.println("player was initially at: " + currentPosition);
while (currentPosition.getX() > destinationPosition.getX()
&& currentPosition.getY() > destinationPosition.getY()) {
Point2D.Double nextPosition = MyVelocityCalculator.getVelocity(currentPosition, destinationPosition, speed);
System.out.println("half seconds later player should be at: " + nextPosition);
currentPosition = nextPosition;
}
System.out.println("player destination is at: " + destinationPosition);
}
public static final Point2D.Double getVelocity(Point2D.Double currentPosition, Point2D.Double destinationPosition,
double speed) {
Point2D.Double nextPosition = new Point2D.Double();
double angle = calcAngleBetweenPoints(currentPosition, destinationPosition);
double distance = speed;
Point2D.Double velocityPoint = getVelocity(angle, distance);
nextPosition.x = currentPosition.x + velocityPoint.x;
nextPosition.y = currentPosition.y + velocityPoint.y;
return nextPosition;
}
public static final double calcAngleBetweenPoints(Point2D.Double p1, Point2D.Double p2) {
return Math.toDegrees(Math.atan2(p2.getY() - p1.getY(), p2.getX() - p1.getX()));
}
public static final Point2D.Double getVelocity(double angle, double speed) {
double x = Math.cos(Math.toRadians(angle)) * speed;
double y = Math.sin(Math.toRadians(angle)) * speed;
return (new Point2D.Double(x, y));
}
}
Instead of print out the position on console you need to draw the control at this position to you graphics element.

Rounding Inaccuracies When Combining Areas in Java?

I'm working with Areas in Java.
My test program draws three random triangles and combines them to form one or more polygons. After the Areas are .add()ed together, I use PathIterator to trace the edges.
Sometimes, however, the Area objects will not combine as they should... and as you can see in the last image I posted, extra edges will be drawn.
I think the problem is caused by rounding inaccuracies in Java's Area class (when I debug the test program, the Area shows the gaps before the PathIterator is used), but I don't think Java provides any other way to combine shapes.
Any solutions?
Example code and images:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Area;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
public class AreaTest extends JFrame{
private static final long serialVersionUID = -2221432546854106311L;
Area area = new Area();
ArrayList<Line2D.Double> areaSegments = new ArrayList<Line2D.Double>();
AreaTest() {
Path2D.Double triangle = new Path2D.Double();
Random random = new Random();
// Draw three random triangles
for (int i = 0; i < 3; i++) {
triangle.moveTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.closePath();
area.add(new Area(triangle));
}
// Note: we're storing double[] and not Point2D.Double
ArrayList<double[]> areaPoints = new ArrayList<double[]>();
double[] coords = new double[6];
for (PathIterator pi = area.getPathIterator(null); !pi.isDone(); pi.next()) {
// Because the Area is composed of straight lines
int type = pi.currentSegment(coords);
// We record a double array of {segment type, x coord, y coord}
double[] pathIteratorCoords = {type, coords[0], coords[1]};
areaPoints.add(pathIteratorCoords);
}
double[] start = new double[3]; // To record where each polygon starts
for (int i = 0; i < areaPoints.size(); i++) {
// If we're not on the last point, return a line from this point to the next
double[] currentElement = areaPoints.get(i);
// We need a default value in case we've reached the end of the ArrayList
double[] nextElement = {-1, -1, -1};
if (i < areaPoints.size() - 1) {
nextElement = areaPoints.get(i + 1);
}
// Make the lines
if (currentElement[0] == PathIterator.SEG_MOVETO) {
start = currentElement; // Record where the polygon started to close it later
}
if (nextElement[0] == PathIterator.SEG_LINETO) {
areaSegments.add(
new Line2D.Double(
currentElement[1], currentElement[2],
nextElement[1], nextElement[2]
)
);
} else if (nextElement[0] == PathIterator.SEG_CLOSE) {
areaSegments.add(
new Line2D.Double(
currentElement[1], currentElement[2],
start[1], start[2]
)
);
}
}
setSize(new Dimension(500, 500));
setLocationRelativeTo(null); // To center the JFrame on screen
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public void paint(Graphics g) {
// Fill the area
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.lightGray);
g2d.fill(area);
// Draw the border line by line
g.setColor(Color.black);
for (Line2D.Double line : areaSegments) {
g2d.draw(line);
}
}
public static void main(String[] args) {
new AreaTest();
}
}
A successful case:
A failing case:
Here:
for (int i = 0; i < 3; i++) {
triangle.moveTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.closePath();
area.add(new Area(triangle));
}
you are adding in fact
1 triangle in the first loop
2 triangles in the second loop
3 triangles in the third loop
This is where your inaccuracies come from. Try this and see if your problem still persists.
for (int i = 0; i < 3; i++) {
triangle.moveTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.lineTo(random.nextInt(400) + 50, random.nextInt(400) + 50);
triangle.closePath();
area.add(new Area(triangle));
triangle.reset();
}
Note the path reset after each loop.
EDIT: to explain more where the inaccuracies come from here the three paths you try to combine. Which makes it obvious where errors might arise.
I've re-factored your example to make testing easier, adding features of both answers. Restoring triangle.reset() seemed to eliminate the artifatcts for me. In addition,
Build the GUI on the event dispatch thread.
For rendering, extend a JComponent, e.g. JPanel, and override paintComponent().
Absent subcomponents having a preferred size, override getPreferredSize().
Use RenderingHints.
SSCCE:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/** #see http://stackoverflow.com/q/9526835/230513 */
public class AreaTest extends JPanel {
private static final int SIZE = 500;
private static final int INSET = SIZE / 10;
private static final int BOUND = SIZE - 2 * INSET;
private static final int N = 5;
private static final AffineTransform I = new AffineTransform();
private static final double FLATNESS = 1;
private static final Random random = new Random();
private Area area = new Area();
private List<Line2D.Double> areaSegments = new ArrayList<Line2D.Double>();
private int count = N;
AreaTest() {
setLayout(new BorderLayout());
create();
add(new JPanel() {
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.lightGray);
g2d.fill(area);
g.setColor(Color.black);
for (Line2D.Double line : areaSegments) {
g2d.draw(line);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
});
JPanel control = new JPanel();
control.add(new JButton(new AbstractAction("Update") {
#Override
public void actionPerformed(ActionEvent e) {
create();
repaint();
}
}));
JSpinner countSpinner = new JSpinner();
countSpinner.setModel(new SpinnerNumberModel(N, 3, 42, 1));
countSpinner.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
JSpinner s = (JSpinner) e.getSource();
count = ((Integer) s.getValue()).intValue();
}
});
control.add(countSpinner);
add(control, BorderLayout.SOUTH);
}
private int randomPoint() {
return random.nextInt(BOUND) + INSET;
}
private void create() {
area.reset();
areaSegments.clear();
Path2D.Double triangle = new Path2D.Double();
// Draw three random triangles
for (int i = 0; i < count; i++) {
triangle.moveTo(randomPoint(), randomPoint());
triangle.lineTo(randomPoint(), randomPoint());
triangle.lineTo(randomPoint(), randomPoint());
triangle.closePath();
area.add(new Area(triangle));
triangle.reset();
}
// Note: we're storing double[] and not Point2D.Double
List<double[]> areaPoints = new ArrayList<double[]>();
double[] coords = new double[6];
for (PathIterator pi = area.getPathIterator(I, FLATNESS);
!pi.isDone(); pi.next()) {
// Because the Area is composed of straight lines
int type = pi.currentSegment(coords);
// We record a double array of {segment type, x coord, y coord}
double[] pathIteratorCoords = {type, coords[0], coords[1]};
areaPoints.add(pathIteratorCoords);
}
// To record where each polygon starts
double[] start = new double[3];
for (int i = 0; i < areaPoints.size(); i++) {
// If we're not on the last point, return a line from this point to the next
double[] currentElement = areaPoints.get(i);
// We need a default value in case we've reached the end of the List
double[] nextElement = {-1, -1, -1};
if (i < areaPoints.size() - 1) {
nextElement = areaPoints.get(i + 1);
}
// Make the lines
if (currentElement[0] == PathIterator.SEG_MOVETO) {
// Record where the polygon started to close it later
start = currentElement;
}
if (nextElement[0] == PathIterator.SEG_LINETO) {
areaSegments.add(
new Line2D.Double(
currentElement[1], currentElement[2],
nextElement[1], nextElement[2]));
} else if (nextElement[0] == PathIterator.SEG_CLOSE) {
areaSegments.add(
new Line2D.Double(
currentElement[1], currentElement[2],
start[1], start[2]));
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame();
f.add(new AreaTest());
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setVisible(true);
}
});
}
}
I played around with this, and found a hacky way of getting rid of these. I'm not 100% sure that this will work in all cases, but it might.
After reading that the Area.transform's JavaDoc mentions
Transforms the geometry of this Area using the specified
AffineTransform. The geometry is transformed in place, which
permanently changes the enclosed area defined by this object.
I had a hunch and added possibility of rotating the Area by holding down a key. As the Area was rotating, the "inward" edges started to slowly disappear, until only the outline was left. I suspect that the "inward" edges are actually two edges very close to each other (so they look like a single edge), and that rotating the Area causes very small rounding inaccuracies, so the rotating sort of "melts" them together.
I then added a code to rotate the Area in very small steps for a full circle on keypress, and it looks like the artifacts disappear:
The image on the left is the Area built from 10 different random triangles (I upped the amount of triangles to get "failing" Areas more often), and the one on the right is the same Area, after being rotated full 360 degrees in very small increments (10000 steps).
Here's the piece of code for rotating the area in small steps (smaller amounts than 10000 steps would probably work just fine for most cases):
final int STEPS = 10000; //Number of steps in a full 360 degree rotation
double theta = (2*Math.PI) / STEPS; //Single step "size" in radians
Rectangle bounds = area.getBounds(); //Getting the bounds to find the center of the Area
AffineTransform trans = AffineTransform.getRotateInstance(theta, bounds.getCenterX(), bounds.getCenterY()); //Transformation matrix for theta radians around the center
//Rotate a full 360 degrees in small steps
for(int i = 0; i < STEPS; i++)
{
area.transform(trans);
}
As I said before, I'm not sure if this works in all cases, and the amount of steps needed might be much smaller or larger depending on the scenario. YMMV.

Categories

Resources