Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Graphics - Keeping track of shapes

So I am making an application and I want to keep track of the shapes added to the screen. I have the following code so far, but when a circle is added it cannot be moved/changed. Ideally, I'd want something like shift-click to move it around/highlight it.

I'm also wondering how I could make it so that you can drag a line from one circle to another. I don't know if I'm using the wrong tools for the job here but any help would be appreciated.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MappingApp extends JFrame implements MouseListener { 

  private int x=50;   // leftmost pixel in circle has this x-coordinate
  private int y=50;   // topmost  pixel in circle has this y-coordinate

  public MappingApp() {
    setSize(800,800);
    setLocation(100,100);
    addMouseListener(this); 
    setVisible(true);
  }

  // paint is called automatically when program begins, when window is
  //   refreshed and  when repaint() is invoked 
  public void paint(Graphics g) {
    g.setColor(Color.yellow);
    g.fillOval(x,y,100,100);

}

  // The next 4 methods must be defined, but you won't use them.
  public void mouseReleased(MouseEvent e ) { }
  public void mouseEntered(MouseEvent e)   { }
  public void mouseExited(MouseEvent e)    { }
  public void mousePressed(MouseEvent e)   { }

  public void mouseClicked(MouseEvent e) { 
    x = e.getX();   // x-coordinate of the mouse click
    y = e.getY();   // y-coordinate of the mouse click
    repaint();    //calls paint()
  }

  public static void main(String argv[]) {
    DrawCircle c = new DrawCircle();
  }
}
like image 315
Tim Avatar asked Jan 13 '23 01:01

Tim


1 Answers

Use java.awt.geom.* to create shapes, use fields to reference them and then use the graphics object to draw them.

for eg:

Ellipse2D.Float ellipse=new Ellipse2D.Float(50,50,100,100);

graphics.draw(ellipse);
like image 70
Nikki Avatar answered Jan 16 '23 01:01

Nikki