Disegno di un poligono clickando sui vertici

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;
    private int i=0;
    private int[] ascisse=new int[50];
    private int[] ordinate=new int[50];
    private int numero=5;
    public Retta(){
        addMouseListener(this);
    }
    @Override public void mouseClicked(MouseEvent e){

    }
    @Override public void mouseEntered(MouseEvent e){

    }
    @Override public void mouseExited(MouseEvent e){

    }
    @Override public void mousePressed(MouseEvent e){
        ascisse[i]=e.getX();
        ordinate[i]=e.getY();
        i++;
        if(i>numero-1){
            i=0;
            repaint();
        }
    }
    @Override public void mouseReleased(MouseEvent e){
    }
    @Override public void paintComponent(Graphics g){
        int j=0;
        g.setColor(Color.red);
        for(j=0;j<numero-1;j++){
                g.drawLine(ascisse[j], ordinate[j], ascisse[j+1], ordinate[j+1]);
        }
        g.drawLine(ascisse[0], ordinate[0], ascisse[j], ordinate[j]);
    }
}

 

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