I tried to make a simple program, draw a 4 sided polygon with 4 mouse clicks. This is the code:

import acm.graphics.*;
import acm.program.*;
import java.awt.event.*;

public class Pravougaonik extends GraphicsProgram {
    public void run() {
        addMouseListeners();   
    }
    public void mouseClicked(MouseEvent e) {
        GPolygon cetvorougao = new GPolygon();
        cetvorougao.addVertex(e.getX(),e.getY());
        cetvorougao.addVertex(e.getX(),e.getY());
        cetvorougao.addVertex(e.getX(),e.getY());
        cetvorougao.addVertex(e.getX(),e.getY());
        add(cetvorougao);       
    }
}

I understand that the problem is when I click once all 4 vertices have the same coordinates, but I don't know how to correct the code. Can anyone help??

Recommended Answers

All 2 Replies

You declare and initialise cetvorougao inside your mouseClicked, so every time the mouse is clicked you create a new cetvorougao, which is garbage collected at the end of the method. You need to declare and initialise it inside the class but outside any method so there is just one instance of it that is shared between all methods and executions of any method.

Finally, I have the solution.
Here is the code, so anybody can see the solution.

public class Pravougaonik extends GraphicsProgram {
  private GPolygon cetvorougao;
  private int count = 0;

  public void run() {
    addMouseListeners();    
  }
  public void mouseClicked(MouseEvent e) {
    if (count == 0) {
      cetvorougao = new GPolygon();
    }
    cetvorougao.addVertex(e.getX(),e.getY());
    count++;
    if (count == 4) {
      add(cetvorougao);
      count = 0;
    }
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.