growbox.java

Download: growbox.zip

See also Rect.java

Reference

ArrayList


growbox.java

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


class growbox extends JPanel implements MouseMotionListener
{
    ArrayList<Rect> boxes;
    Point base, current;
    Rect r;
    boolean isDragging;
    
    growbox()
    {
	isDragging = false;
	boxes = new ArrayList<Rect>();
	addMouseListener(new MouseHandler());
	addMouseMotionListener(this);
    }

    public void paintComponent(Graphics g)
    {
	super.paintComponent(g);
	if (boxes.size()==0) return;

	for (Rect r: boxes) r.draw(g);
	if (boxes.size()>1) showIntersect(g);
    }

    public void showIntersect(Graphics g)
    {
	Rect a, b, c;
	a = boxes.get(0);
	b = boxes.get(1);
	    
	c = Rect.bounding(a,b);
	c.fillcolor = Color.cyan;
	    // c.draw(g);
	c = Rect.intersection(a,b);
	if (c!=null) {
	    c.fillcolor = Color.red;
	    if (a.contains(b) || b.contains(a)) c.fillcolor = Color.blue;
	    c.draw(g);
	}
    }


    private class MouseHandler extends MouseAdapter
    {

	public void mousePressed(MouseEvent event)
	{
	    current = event.getPoint();
	    base = event.getPoint();
	}

	public void mouseReleased(MouseEvent event)
	{
	    isDragging = false;
	    current = event.getPoint();

	    Graphics g = getGraphics();
	    g.setXORMode(Color.WHITE);
	    r.fastdraw(g);
	    g.setPaintMode();
	    g.setColor(Color.BLACK);
	    Rect rg = new Rect(base.x,base.y,current.x,current.y);
	    if (boxes.size()>1) boxes.remove(1);
	    if (rg.area()>1) boxes.add(rg);
	    repaint();
	}
    }

    public void mouseDragged(MouseEvent event)
    {
	Graphics g = getGraphics();
	int bx = base.x;
	int by = base.y;
	g.setXORMode(Color.WHITE);
	if (isDragging) {
	    //r = new Rect(bx,by,current.x,current.y);
	    r.fastdraw(g);
	}
	isDragging = true;
	current = event.getPoint();
	r = new Rect(bx,by,current.x,current.y);
	r.fastdraw(g);
	g.setPaintMode();
	g.setColor(Color.BLACK);
    }

    public void mouseMoved(MouseEvent event)
    {
    }

   public static void main(String[] args)
   {
       EventQueue.invokeLater(new Runnable() {
	   public void run()
	   {
	       growbox panel = new growbox();
	       JFrame frame = new JFrame("Grow Box");
	       frame.add(panel);
	       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	       frame.setSize(400,400);
	       frame.setVisible(true);
	   }
       });
   }
}


Maintained by John Loomis, updated Sun Mar 15 16:19:36 2020