Question

Java Programing. Using NetBean Write a program to draw a line connecting two circles. These two circles can be dragged by mouse. And when circles are dragged, the line should be adjusted so that it st...

Java Programing.

Using NetBean

Write a program to draw a line connecting two circles. These two circles can be dragged by mouse. And when circles are dragged, the line should be adjusted so that it still connect these two circles (binding property)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private Ellipse2D circle1;
private Ellipse2D circle2;

private Point2D drawTo;

public TestPane() {
circle1 = new Ellipse2D.Double(10, 10, 40, 40);
circle2 = new Ellipse2D.Double(100, 150, 40, 40);

//addMouseMotionListener(new MouseAdapter() {
// @Override
// public void mouseMoved(MouseEvent e) {
// drawTo = new Point2D.Double(e.getPoint().x, e.getPoint().y);
// repaint();
// }
//});
}

protected Point2D center(Rectangle2D bounds) {
return new Point2D.Double(bounds.getCenterX(), bounds.getCenterY());
}

protected double angleBetween(Shape from, Shape to) {
return angleBetween(center(from.getBounds2D()), center(to.getBounds2D()));
}

protected double angleBetween(Point2D from, Point2D to) {
double x = from.getX();
double y = from.getY();

// This is the difference between the anchor point
// and the mouse. Its important that this is done
// within the local coordinate space of the component,
// this means either the MouseMotionListener needs to
// be registered to the component itself (preferably)
// or the mouse coordinates need to be converted into
// local coordinate space
double deltaX = to.getX() - x;
double deltaY = to.getY() - y;

// Calculate the angle...
// This is our "0" or start angle..
double rotation = -Math.atan2(deltaX, deltaY);
rotation = Math.toRadians(Math.toDegrees(rotation) + 180);

return rotation;
}

protected Point2D getPointOnCircle(Shape shape, double radians) {
Rectangle2D bounds = shape.getBounds();
// Point2D point = new Point2D.Double(bounds.getX(), bounds.getY());
Point2D point = center(bounds);
return getPointOnCircle(point, radians, Math.max(bounds.getWidth(), bounds.getHeight()) / 2d);
}

protected Point2D getPointOnCircle(Point2D center, double radians, double radius) {

double x = center.getX();
double y = center.getY();

radians = radians - Math.toRadians(90.0); // 0 becomes th?e top
// Calculate the outter point of the line
double xPosy = Math.round((float) (x + Math.cos(radians) * radius));
double yPosy = Math.round((float) (y + Math.sin(radians) * radius));

return new Point2D.Double(xPosy, yPosy);

}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.draw(circle1);
g2d.draw(circle2);

// This was used for testing, it will draw a line from circle1 to the
// drawTo point, which, if enabled, is the last known position of the
// mouse
//if (drawTo != null) {
// Point2D pointFrom = center(circle1.getBounds2D());
// g2d.setColor(Color.RED);
// g2d.draw(new Line2D.Double(drawTo, pointFrom));
//
// double from = angleBetween(pointFrom, drawTo);
// System.out.println(NumberFormat.getNumberInstance().format(Math.toDegrees(from)));
//
// Point2D poc = getPointOnCircle(circle1, from);
// g2d.setColor(Color.BLUE);
// g2d.draw(new Line2D.Double(poc, drawTo));
//}

double from = angleBetween(circle1, circle2);
double to = angleBetween(circle2, circle1);

Point2D pointFrom = getPointOnCircle(circle1, from);
Point2D pointTo = getPointOnCircle(circle2, to);

g2d.setColor(Color.RED);
Line2D line = new Line2D.Double(pointFrom, pointTo);
g2d.draw(line);
g2d.dispose();
}

}

}

Add a comment
Know the answer?
Add Answer to:
Java Programing. Using NetBean Write a program to draw a line connecting two circles. These two circles can be dragged by mouse. And when circles are dragged, the line should be adjusted so that it st...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java Programing. Using NetBean Write a program to draw a line connecting two circles. These two...

    Java Programing. Using NetBean Write a program to draw a line connecting two circles. These two circles can be dragged by mouse. And when circles are dragged, the line should be adjusted so that it still connect these two circles (binding property)

  • 2) Write a Python program that draw simple lollipop (a line and few circles, the line should atta...

    2) Write a Python program that draw simple lollipop (a line and few circles, the line should attach to the circles, just as regular lollipop, you decide the colors), just as we make a "dart" for assignment. You can use the same idea when we make "target" by making few circles with different colors, and using mouse click get 2 points to draw a line. See sample program from Zelle textbook, chapter 4, click.pyw and triangle.pyw. Or see assignment archery.pyw....

  • Java Using NetBean Write a program that can dynamically change the font of a message. The font name or font size can be chosen from combo boxes. The font name can be Dialog, DialogInput, Monospaced, S...

    Java Using NetBean Write a program that can dynamically change the font of a message. The font name or font size can be chosen from combo boxes. The font name can be Dialog, DialogInput, Monospaced, Serif, or SansSerif. The font style can be selected as PLAIN, BOLD and/or ITALIC. Font myFont = new Font("Serif", Font.PLAIN, 12); message.setFont(myFont);

  • In Python: Write a program that determines whether two circles intersect. The input should consist of...

    In Python: Write a program that determines whether two circles intersect. The input should consist of six numbers, x1, y1, r1 and x2, y2, r2, given as command-line arguments, and representing the center and radius of the two circles. Your program should print True if the two circles intersect, and False otherwise. As a reminder, the two circles intersect if and only if the distance of their two centers is less than or equal to the sum of their two...

  • Use WebGL to write a program that plays tic-tac-toe. The program should begin by drawing the...

    Use WebGL to write a program that plays tic-tac-toe. The program should begin by drawing the game board (two vertical lines and two horizontal lines). When a player left-clicks on an open space, the program should draw an “X” in that square. When a player right-clicks on an open space, the program should draw an “O” in that square. The Xs must be different colors from the Os. Both of those colors must be different from the lines making the...

  • FOR JAVA Write a program that takes two command line arguments: an input file and an...

    FOR JAVA Write a program that takes two command line arguments: an input file and an output file. The program should read the input file and replace the last letter of each word with a * character and write the result to the output file. The program should maintain the input file's line separators. The program should catch all possible checked exceptions and display an informative message. Notes: This program can be written in a single main method Remember that...

  • Use Java language to create this program Write a program that allows two players to play...

    Use Java language to create this program Write a program that allows two players to play a game of tic-tac-toe. Using a two-dimensional array with three rows and three columns as the game board. Each element of the array should be initialized with a number from 1 - 9 (like below): 1 2 3 4 5 6 7 8 9 The program should run a loop that Displays the contents of the board array allows player 1 to select the...

  • Assignment on Java programing 1. Write programs for the following exercises in Java. Each file should...

    Assignment on Java programing 1. Write programs for the following exercises in Java. Each file should have short description of the implemented class and for files with main method the problem it is solving. Make sure your files have appropriate names. Programs should write output to the Console. b) BST: Implement Binary Search Tree ADT with insert(int key), delete(int key), Node find(int key), and in-order traverse() where it prints the value of the key. Your operations should use recursion. The...

  • Can some please help me to answer these two questions. Write a program in Java create...

    Can some please help me to answer these two questions. Write a program in Java create a class diagram fragment with two classes: User and Patient. Patient is a sub-class of User. User has a method getName(), which is both over-loaded and over-ridden in the subclass In Java write an abstract class called User. User has one abstract method called authenticate, which takes two string parameters. Write a concrete sub-class of User called Administrator with an implementation of the authenticate...

  • Write in Java! Do NOT write two different programs for Deck and Card, it should be...

    Write in Java! Do NOT write two different programs for Deck and Card, it should be only one program not 2 separate ones!!!!!! The Learning Goal for this exercise is to use and understand and know the difference between arrays and array lists. !!!!Use at least one array defined in your code and two array lists defined by the operation of your code!!!! The array should be 52 elements and contain a representation of a standard deck of cards, in...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT