0

Viewer for a triangle

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Viewer
{
  static int counter = 0;
  static double x1, x2, x3, y1, y2, y3;
  public static void main (String [] args)
  {
    JFrame outerFrame = new JFrame();
    JPanel panel = new JPanel();



    outerFrame.add(panel);
    panel.addMouseListener(new MouseAdapter(){

      @Override
      public void mousePressed(MouseEvent e){
        if(counter == 0) {
          x1 = e.getX();
          y1 = e.getY();
        } else if(counter == 1) {
          x2 = e.getX();
          y2 = e.getY();
        } else if(counter == 2) {
          x3 = e.getX();
          y3 = e.getY();
        }
        counter++;
      }
    });


    TriangleComponent component = new TriangleComponent(x1, x2, x3, y1, y2, y3);

    outerFrame.add(component);
    outerFrame.setSize(400, 400);
    outerFrame.setTitle("Drawing Triangle");
    outerFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    outerFrame.setVisible(true);

  }
}

Component

import java.awt.*;
import javax.swing.*;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;



public class TriangleComponent extends JComponent 
{
  private double x1, x2, x3, y1, y2, y3;
  public TriangleComponent(double xOne, double xTwo, double xThree, double yOne, double yTwo, double yThree) {
    x1 = xOne;
    x2 = xTwo;
    x3 = xThree;
    y1 = yOne;
    y2 = yTwo;
    y3 = yThree;
  }
  public void paintComponent(Graphics triangle) 
  {    
    Point2D.Double L = new Point2D.Double(x1, y1);
    Point2D.Double R = new Point2D.Double(x2, y2);
    Point2D.Double M = new Point2D.Double(x3, y3);


    Line2D.Double leftSegment = new Line2D.Double(L, R);
    Line2D.Double rightSegment = new Line2D.Double(R, M);    
    Line2D.Double baseSegment = new Line2D.Double(M, L);

    Graphics2D tri = (Graphics2D) triangle;
    tri.setPaint(Color.RED);
    tri.setStroke(new BasicStroke(5));
    tri.draw(leftSegment);
    tri.draw(rightSegment);
    tri.draw(baseSegment);
  }
}

I am trying to get my x and y values through the mouse listener, but I think I have a problem, for nothing happens after three clicks, and there is a point at the very left of the frame.

  • You need to add a mouselistener to the area where you are drawing. You can easily get the points X and Y coordinates when they click from this. – Alex Oct 25 '15 at 17:06
  • It would be easy if I knew anything... I added a mouse listener to the area but how can I get the values to the component? – Armanc Keser Oct 25 '15 at 17:37
  • from the mouselistener then you should have methods like mouseClicked(MouseEvent e) . You then can do like e.getX() to find it's x coordinate – Alex Oct 25 '15 at 18:22

0 Answers0