Disegnare la retta passante per due punti clickati col mouse

import java.awt.event.*;

import java .awt.*;

import javax.swing.*;

public class Retta extends JPanel implements MouseListener {

   private int x1;

   private int y1;

   private int x2;

   private int y2;

   private int conta=0;

   public Retta(){

   addMouseListener(this);

   }

   @Override public void mouseClicked(MouseEvent e){

   int x=e.getX();

   int y=e.getY();

   conta++;

   if(conta==1){

   x1=x;

   y1=y;

   }

   if(conta==2){

   x2=x;

   y2=y;

   conta=0;

   repaint();

   }

   }

   @Override public void mouseEntered(MouseEvent e){

   }

   @Override public void mouseExited(MouseEvent e){

   }

   @Override public void mousePressed(MouseEvent e){

   }

   @Override public void mouseReleased(MouseEvent e){

 

   }

   @Override public void paintComponent(Graphics g){

   g.drawLine(x1, y1, x2, y2);

   }

}


import java.awt.*;import javax.swing.*;public class TestaRetta {   public static void main(String Args[]){   Retta r1=new Retta();   JFrame f1=new JFrame("Retta");   f1.setSize(500,500);   f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   f1.add(BorderLayout.CENTER,r1);   f1.setVisible(true);   }}


Commenti