Get user input for drawingpanel and use it in another method - java

I am very new to java and I need a little help on a an assignment. The assignment was to get user input (radius, x-coordinate, & y-coordinate) to draw 3 different colored circles in a drawingPanel, I have that part down. The second part asks us for a static method that compares the radii of two circles and lets the user know if one is smaller, bigger, or the same size as the other. I am having trouble figuring out how to use the input for the radii in the method that compares the two.
Here is my code so far:
import java.awt.*;
import java.util.*;
public class Circles {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void blueCircle(Graphics g) {
g.setColor(Color.BLUE);
int r = CONSOLE.nextInt();
int x = CONSOLE.nextInt();
int y = CONSOLE.nextInt();
g.fillOval(0 + x, 0 + y, r * 2, r * 2);
}
public static void greenCircle(Graphics g) {
g.setColor(Color.GREEN);
int r = CONSOLE.nextInt();
int x = CONSOLE.nextInt();
int y = CONSOLE.nextInt();
g.fillOval(0 + x, 0 + y, r * 2, r * 2);
}
public static void redCircle(Graphics g) {
g.setColor(Color.RED);
int r = CONSOLE.nextInt();
int x = CONSOLE.nextInt();
int y = CONSOLE.nextInt();
g.fillOval(0 + x, 0 + y, r * 2, r * 2);
}
public static void compareCircles(int r1, int r2) {
int x;
if (r1 < r2)
x = -1;
if (r1 == r2)
x = 0;
if (r1 > r2)
x = 1;
return;
}
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(400, 300);
Graphics g = panel.getGraphics();
System.out.println("Enter values for the radius, x , & y-coordinates of blue circle: ");
blueCircle(g);
System.out.println("Enter values for the radius, x , & y-coordinates of green circle: ");
greenCircle(g);
System.out.println("Enter values for the radius, x , & y-coordinates of red circle: ");
redCircle(g);
}
}

You can reduce the code reuse in your implementation. Make a generic method for create the circle for given input parameters.
public static void blueCircle(Graphics g, int r, int x, int y, Color c) {
g.setColor(c);
g.fillOval(0 + x, 0 + y, r * 2, r * 2);
}
Then one generic method for radii comparison.
public static String compareCircles(int r1, int r2) {
String output = "";
if (r1 < r2)
output = r1+" circle is smaller than "+r2;
if (r1 == r2)
output = "both circles are in same size.";
if (r1 > r2)
output = r1+" circle is larger than "+r2;
return output;
}
Now within the main mehod get the necessary inputs and pass them to these methods.
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(400, 300);
Graphics g = panel.getGraphics();
System.out.println("Enter values for the radius, x , & y-coordinates of blue circle: ");
int rBlue = CONSOLE.nextInt();
int xBlue = CONSOLE.nextInt();
int yBlue = CONSOLE.nextInt();
// Better to do the validation for the user inputs
blueCircle(g, rBlue, xBlue, yBlue, Color.BLUE);
// Do the same thing for the other two circles.
// Then call the comparison method with your r input values like below.
//String output = compareCircles(rBlue, rGreen);
}
Hope this is what you are looking for..

Related

Trying to create a 5x5 grid of squares with std draw but squares are at duplicate coordinates

I am trying to create a 5x5 board of rectangles(squares) with a 2d array but my code draws the 25 squares in only 5 places so it looks like there's only 5 squares diagonally on the "board". I'm assuming something is wrong with the logic in the nested loop but after tinkering around for a while I can't figure out what it is. Thanks for any help!!
Object class:
public class Card
{
private double x, y, wd, ht;
private int cardNum;
private boolean faceUp;
private double space;
private Color bsC, fsC;
Random gen = new Random();
public Card(double x, double y, double width, double height, int cN, double sP)
{
this.x = x;
this.y = x;
wd = width;
ht = height;
faceUp = false;
this.cardNum = cN;
space = 0.1;
bsC = new Color(178, 178, 178);
fsC = new Color(211, 172, 250);
}
public void drawMe()
{
StdDraw.setPenColor(bsC);
StdDraw.filledRectangle(x, y, wd, ht);
}
}
Tester class:
public class ClientCardJordanHubbard
{
public static void ClientCardJordanHubbard()
{
Random gen = new Random();
Card[][] cards = new Card[5][5];
int count = 0;
StdDraw.setFont(new Font("Arial", Font.BOLD, 20));
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.text(0.5,0.5, "Press w a s d to move");
StdDraw.pause(2000);
StdDraw.clear();
for(int i = 0; i < cards.length; i++)
{
double x = 0.25+0.14*i;
for (int j = 0; j < cards[i].length; j++)
{
double y = 0.25+0.14*j;
double w = 0.07;
double h = 0.07;
int cN = gen.nextInt(5)+1;
cards[i][j] = new Card(x, y, w, h, cN, 0.1);
cards[i][j].drawMe();
System.out.println("The value of the card at index " +i+" " +j
+ " is: " +cards[i][j].getcN());
System.out.println("The coordinates of the card at index " +i+" " +j
+ " is: " +cards[i][j].getX() +" "+cards[i][j].getY());
}
}
}
Since your cards are displayed diagonally, the first thing you need to check whether your x will get an y value or vice-versa at some point. Knowing this, it is easy to find the error, which is the line of
this.y = x;
since your this.y gets an x value.

Why won't this take the stuff for color and use it to decide the colors?

//im trying to get this to take the method I created for color so that It could create different shades of red
import java.util.Scanner;
public class Pop {
public static void main(String[] args) throws java.io.IOException {
StdDraw.enableDoubleBuffering();
java.util.Scanner scan = new java.util.Scanner(new java.io.FileReader("numfile.txt"));
int a = scan.nextInt();
int b = scan.nextInt();
int c = scan.nextInt();
//asks user for input to choose colors
Scanner myObj = new Scanner(System.in);
System.out.println("Enter a number between 1 and 10");
int number = myObj.nextInt(); // Read user input
System.out.println("The number you selected is " + number + ". Good choice! One moment...");
//creates new variables by multiplying the input number and file numbers
StdDraw.enableDoubleBuffering();
rerectangle(0.0, 0.5);
color(a*number);
StdDraw.show();
}
static void rerectangle(double x, double radius) {
if (radius > 0.01) {
StdDraw.setPenColor(color(), 0, 0);
StdDraw.filledRectangle(0.5, radius, radius, radius);
rerectangle(x + radius * 0.2, radius * 0.9);
}
}
static int color(int color1) {
return (color1 * 2);
}
}

Why can't I call new polygon?

My teacher gave me this
In a n - sided regular polygon, all sides have the same length and all angles have the same degree. Design a class named RegularPolygon that contains:
A private int data field named n that defines the number of sides in the Polygon with default value 3.
A private double data field named side that stores the length of the side with default value 1.
A private double data field named X that defines the x - coordinate of the polygon’s center with default value 0.
A private double data field named Y that defines the y - coordinate of the polygon’s center with default value 0.
A constructor that creates a regular polygon with the specified number of sides, length of side, and x - and y- coordinates (values are passed from the parameters to the fields).
The accessor methods for all data fields.
The method getPerimeter() that returns the perimeter of the polygon.
The method getArea() that returns the area of the polygon. The formula is Area = n * s*s / (4 * tan(PI / n)).
2) Write a RegularPolygonTest class, allow the user to enter the data fields, and your program prints out the perimeter and the area of the regular polygon.
This is my code so far:
public class RegularPolygon{
private int n;
private double side, x, y;
public RegularPolygon(){
n = 3;
side = 1;
x = 0;
y = 0;
}
public RegularPolygon(int n, double side){
this.n = n;
this.side = side;
x = 0;
y = 0;
}
public RegularPolygon(int sn, double length, double x_coord, double y_coord){
n = sn;
side = length;
x = x_coord;
y = y_coord;
}
//set n to the user input
public void setN(int other){
n = other;
}
public int getN(){
return n;
}
//set side to userinput
public void setSide(double otherside){
side = otherside;
}
public double getSide(){
return side;
}
//set x to user input
public void setX(int x_co){
x = x_co;
}
public double getX(){
return x;
}
//set y to user input
public void setY(int they){
y = they;
}
public double getY(){
return y;
}
//find perimeter
public double getPerimeter(){
return n * side;
}
//find area
public double getArea(){
double s_squ = side * side;
double pin = Math.PI/n;
double tangent = Math.tan(pin);
return (n*s_squ)/(4*tangent);
}
}
import java.util.Scanner;
public class RegularPolygonTest{
public static void main(String[] args){
Scanner yer = new Scanner(System.in);
//number of sides
System.out.println("Enter number of sides: ");
int sn = yer.nextInt();
//length of sides
System.out.println("Enter length of sides: ");
double length = yer.nextDouble();
//x-coord
System.out.println("Enter the x-coordinate of the center: ");
double x_coord = yer.nextDouble();
//y-coord
System.out.println("Enter the y-coordinate of the center: ");
double y_coord = yer.nextDouble();
if (x_coord == 0 && y_coord == 0){
RegularPolygon rp = new RegularPolygon(sn, length);
}
else if (sn > 3 && length > 1){
RegularPolygon rp = new RegularPolygon(sn, length, x_coord, y_coord);
}
else{
RegularPolygon rp = new RegularPolygon();
}
System.out.println("The perimeter of the " + rp.getN() + "-sided polygon is : "+ rp.getPerimeter() +". And the are is : "+ rp.getArea());
}
}
The error I get is that the IDE can't find symbol and it points to all of the rp in the last line. How might I fix this error?
All the rp are inside blocks. You need to define a possibly uninitialized rp before the ifs and use this common rp within the ifs.

Implement a subclass Square that extends the Rectangle class

//Implement a subclass Square that extends the Rectangle class. In the constructor,
accept the x- and y-positions of the center and the side length of the square. Call the
setLocation and setSize methods of the Rectangle class. Look up these methods in the
documentation for the Rectangle class. Also supply a method getArea that computes
and returns the area of the square. Write a sample program that asks for the center
and side length, then prints out the square (using the toString method that you
inherit from Rectangle) and the area of the square.
//Ok... So this is last minute, but I don't understand what is wrong with my code it is giving me the error that square cannot be resolved to a type... So here is my Class:
import java.awt.Rectangle;
public class Squares22 extends Rectangle
{
public Squares22(int x, int y, int length) {
setLocation(x - length / 2, y - length / 2);
setSize(length, length);
}
public int getArea() {
return (int) (getWidth() * getHeight());
}
public String toString() {
int x = (int) getX();
int y = (int) getY();
int w = (int) getWidth();
int h = (int) getHeight();
return "Square[x=" + x + ",y=" + y + ",width=" + w + ",height=" + h
+ "]";
}
}
//And this is my tester class...
import java.util.Scanner;
public class Squares22Tester
{
public static void main(String[] args)
{
Scanner newScanx = new Scanner(System.in);
Scanner newScany = new Scanner(System.in);
Scanner newScanl = new Scanner(System.in);
System.out.println("Enter x:");
String x2 = newScanx.nextLine();
System.out.println("Enter y:");
String y2 = newScany.nextLine();
System.out.println("Enter length:");
String l2 = newScanl.nextLine();
int x = Integer.parseInt(x2);
int y = Integer.parseInt(y2);
int length = Integer.parseInt(l2);
Square sq = new Square(x, y, length);
System.out.println(sq.toString());
}
}
//Can anyone please help my assignment is due at midnight.. It says square cannot be resolved to a type on the tester class when compliling....
Square isn't the name of your class. The name of the class is 'Squares22'. This is why 'Square' cannot be recognized.
Change Square in the test to Squares22 or vice versa. This should solve your issues.

Render only the segment/area of a circle that intersects the main circle

I absolutely love maths (or 'math' as most of you would say!) but I haven't done it to a level where I know the answer to this problem. I have a main circle which could have a centre point at any x and y on a display. Other circles will move around the display at will but at any given call to a render method I want to render not only those circles that intersect the main circle, but also only render the segment of that circle that is visible inside the main circle. An analogy would be a shadow cast on a real life object, and I only want to draw the part of that object that is 'illuminated'.
I want to do this preferably in Java, but if you have a raw formula that would be appreciated. I wonder how one might draw the shape and fill it in Java, I'm sure there must be some variation on a polyline with arcs or something?
Many thanks
Let A and B be the 2 intersection points (you can ignore it when there is no, or 1 intercetion point).
Then calculate the length of the circular line segment between A and B.
With this information, you should be able to draw the arc using Graphics' drawArc(...) method (if I'm not mistaken...).
EDIT
Well, you don't even need the length of the circular line segment. I had the line-intersection code laying around, so I built a small GUI around it how you could paint/view the ARC of such intersecting circles (there are a bit of comments in the code):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Arc2D;
/**
* #author: Bart Kiers
*/
public class GUI extends JFrame {
private GUI() {
super("Circle Intersection Demo");
initGUI();
}
private void initGUI() {
super.setSize(600, 640);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
super.setLayout(new BorderLayout(5, 5));
final Grid grid = new Grid();
grid.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
Point p = new Point(e.getX(), e.getY()).toCartesianPoint(grid.getWidth(), grid.getHeight());
grid.showDraggedCircle(p);
}
});
grid.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
Point p = new Point(e.getX(), e.getY()).toCartesianPoint(grid.getWidth(), grid.getHeight());
grid.released(p);
}
#Override
public void mousePressed(MouseEvent e) {
Point p = new Point(e.getX(), e.getY()).toCartesianPoint(grid.getWidth(), grid.getHeight());
grid.pressed(p);
}
});
super.add(grid, BorderLayout.CENTER);
super.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new GUI();
}
});
}
private static class Grid extends JPanel {
private Circle c1 = null;
private Circle c2 = null;
private Point screenClick = null;
private Point currentPosition = null;
public void released(Point p) {
if (c1 == null || c2 != null) {
c1 = new Circle(screenClick, screenClick.distance(p));
c2 = null;
} else {
c2 = new Circle(screenClick, screenClick.distance(p));
}
screenClick = null;
repaint();
}
public void pressed(Point p) {
if(c1 != null && c2 != null) {
c1 = null;
c2 = null;
}
screenClick = p;
repaint();
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, super.getWidth(), super.getHeight());
final int W = super.getWidth();
final int H = super.getHeight();
g2d.setColor(Color.LIGHT_GRAY);
g2d.drawLine(0, H / 2, W, H / 2); // x-axis
g2d.drawLine(W / 2, 0, W / 2, H); // y-axis
if (c1 != null) {
g2d.setColor(Color.RED);
c1.drawOn(g2d, W, H);
}
if (c2 != null) {
g2d.setColor(Color.ORANGE);
c2.drawOn(g2d, W, H);
}
if (screenClick != null && currentPosition != null) {
g2d.setColor(Color.DARK_GRAY);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
Circle temp = new Circle(screenClick, screenClick.distance(currentPosition));
temp.drawOn(g2d, W, H);
currentPosition = null;
}
if (c1 != null && c2 != null) {
g2d.setColor(Color.BLUE);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f));
Point[] ips = c1.intersections(c2);
for (Point ip : ips) {
ip.drawOn(g, W, H);
}
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f));
if (ips.length == 2) {
g2d.setStroke(new BasicStroke(10.0f));
c1.highlightArc(g2d, ips[0], ips[1], W, H);
}
}
g2d.dispose();
}
public void showDraggedCircle(Point p) {
currentPosition = p;
repaint();
}
}
private static class Circle {
public final Point center;
public final double radius;
public Circle(Point center, double radius) {
this.center = center;
this.radius = radius;
}
public void drawOn(Graphics g, int width, int height) {
// translate Cartesian(x,y) to Screen(x,y)
Point screenP = center.toScreenPoint(width, height);
int r = (int) Math.rint(radius);
g.drawOval((int) screenP.x - r, (int) screenP.y - r, r + r, r + r);
// draw the center
Point screenCenter = center.toScreenPoint(width, height);
r = 4;
g.drawOval((int) screenCenter.x - r, (int) screenCenter.y - r, r + r, r + r);
}
public void highlightArc(Graphics2D g2d, Point p1, Point p2, int width, int height) {
double a = center.degrees(p1);
double b = center.degrees(p2);
// translate Cartesian(x,y) to Screen(x,y)
Point screenP = center.toScreenPoint(width, height);
int r = (int) Math.rint(radius);
// find the point to start drawing our arc
double start = Math.abs(a - b) < 180 ? Math.min(a, b) : Math.max(a, b);
// find the minimum angle to go from `start`-angle to the other angle
double extent = Math.abs(a - b) < 180 ? Math.abs(a - b) : 360 - Math.abs(a - b);
// draw the arc
g2d.draw(new Arc2D.Double((int) screenP.x - r, (int) screenP.y - r, r + r, r + r, start, extent, Arc2D.OPEN));
}
public Point[] intersections(Circle that) {
// see: http://mathworld.wolfram.com/Circle-CircleIntersection.html
double d = this.center.distance(that.center);
double d1 = ((this.radius * this.radius) - (that.radius * that.radius) + (d * d)) / (2 * d);
double h = Math.sqrt((this.radius * this.radius) - (d1 * d1));
double x3 = this.center.x + (d1 * (that.center.x - this.center.x)) / d;
double y3 = this.center.y + (d1 * (that.center.y - this.center.y)) / d;
double x4_i = x3 + (h * (that.center.y - this.center.y)) / d;
double y4_i = y3 - (h * (that.center.x - this.center.x)) / d;
double x4_ii = x3 - (h * (that.center.y - this.center.y)) / d;
double y4_ii = y3 + (h * (that.center.x - this.center.x)) / d;
if (Double.isNaN(x4_i)) {
// no intersections
return new Point[0];
}
// create the intersection points
Point i1 = new Point(x4_i, y4_i);
Point i2 = new Point(x4_ii, y4_ii);
if (i1.distance(i2) < 0.0000000001) {
// i1 and i2 are (more or less) the same: a single intersection
return new Point[]{i1};
}
// two unique intersections
return new Point[]{i1, i2};
}
#Override
public String toString() {
return String.format("{center=%s, radius=%.2f}", center, radius);
}
}
private static class Point {
public final double x;
public final double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double degrees(Point that) {
double deg = Math.toDegrees(Math.atan2(that.y - this.y, that.x - this.x));
return deg < 0.0 ? deg + 360 : deg;
}
public double distance(Point that) {
double dX = this.x - that.x;
double dY = this.y - that.y;
return Math.sqrt(dX * dX + dY * dY);
}
public void drawOn(Graphics g, int width, int height) {
// translate Cartesian(x,y) to Screen(x,y)
Point screenP = toScreenPoint(width, height);
int r = 7;
g.fillOval((int) screenP.x - r, (int) screenP.y - r, r + r, r + r);
}
public Point toCartesianPoint(int width, int height) {
double xCart = x - (width / 2);
double yCart = -(y - (height / 2));
return new Point(xCart, yCart);
}
public Point toScreenPoint(int width, int height) {
double screenX = x + (width / 2);
double screenY = -(y - (height / 2));
return new Point(screenX, screenY);
}
#Override
public String toString() {
return String.format("(%.2f,%.2f)", x, y);
}
}
}
If you start the GUI above and then type 100 0 130 -80 55 180 in the text box and hit return, you'll see the following: ...
Changed the code so that circles can be drawn by pressing- and dragging the mouse. Screenshot:
Assuming you know the center point and the radius of the two circles:
Calculate the points where the circles intersect. This can easily be done with trigonometry. There may be no intersection (distance between the center points is longer than the sum of the radiuses, ignorable in your case), one point (distance between center points is equal to the sum of the radiuses, ignorable), or two. Special cases: the circles are identical, or the moving circle ist smaller and completely inside the main circle.
If there are two intersection points: take the center point from the moving circle and draw an arc between those points.
(I have no code for you, but since you love maths... ;-)

Categories

Resources