Calculating distance to center in java

Problem:

Create a java GUI application that creates the distance from a
point specified by a user to the center.

Output:



Prompt Picture Description




Solution:

//*****************DistanceToCenterFrame.java**************/
import javax.swing.JFrame;

public class DistanceToCenterFrame {

 
 public static void main(String[] args) {
  JFrame frame = new JFrame("Distance To Center");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  
  frame.setContentPane(new DistanceToCenterPanel()); 
  frame.pack();
  frame.setVisible(true);
  
 }
}
//*****************DistanceToCenterPanel.java**************/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;

import javax.swing.JPanel;

public class DistanceToCenterPanel extends JPanel{

 
 private final int WIDTH = 600, HEIGHT = 600;
 private int centerX, centerY;
 private double distance;
 private DecimalFormat fmt;
 private Point current;
 
 public DistanceToCenterPanel() {
  centerX = WIDTH/2; 
  centerY = HEIGHT/2;
  distance = 0; current = null;
  fmt = new DecimalFormat("0.##");
  
  addMouseListener(new OffCenterListener());
  
  setPreferredSize(new Dimension(WIDTH, HEIGHT));
  setBackground(Color.YELLOW);
 }
 @Override
 protected void paintComponent(Graphics g) {
  super.paintComponent(g);
  g.setColor(Color.BLACK);
  g.fillOval(centerX-3, centerY-3, 6, 6);
  
  if(current != null) {
   g.drawLine(current.x, current.y, centerX, centerY);
   g.drawString("Distance: " + fmt.format(distance), 5, 15);
  }
 } 
 
 private class OffCenterListener extends MouseAdapter {
  @Override
  public void mouseClicked(MouseEvent e) {
   current = e.getPoint();
   distance = Math.sqrt(Math.pow(current.x-centerX, 2) + Math.pow(current.y-centerY, 2));
   repaint();
   
  }
 }
 
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact