A jigsaw puzzle typically contains a set of pieces of different shapes and sizes
ID: 3559338 • Letter: A
Question
A jigsaw puzzle typically contains a set of pieces of different shapes and sizes. In this assignment, you will write a simple Java program to demonstrate some functionality of a jigsaw puzzle. For simplicity, we will assume that the puzzle pieces are made of two types of polygons only (a polygon is a shape bounded by a finite chain of solid line segments, called edges or sides, such as triangle or rectangle). Design your program as follows:
1. Define an abstract class called Polygon that contains two protected fields (name
Explanation / Answer
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.MouseInputAdapter; public class GraphicDragAndDrop extends JPanel { Rectangle rect; Image img; public GraphicDragAndDrop(String imgFile, int x0, int y0){ rect = new Rectangle(x0, y0, 150, 75); img = new ImageIcon(imgFile).getImage(); } protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setClip(rect); int x = rect.x; int y = rect.y; // here g2d.drawImage(new ImageIcon("a.png").getImage(), x, y, this); } public void setRect(int x, int y) { rect.setLocation(x, y); repaint(); } public static void main(String[] args) { // first piece GraphicDragAndDrop piece1 = new GraphicDragAndDrop("a.png", 0, 0); piece1.setRect(0, 0); new GraphicDragController(piece1); // second piece --> only this will be visible GraphicDragAndDrop piece2 = new GraphicDragAndDrop("a.png", 200, 200); //GraphicDragAndDrop piece2 = new GraphicDragAndDrop("b.png", 200, 200); // does'n work either piece2.setRect(150, 150); new GraphicDragController(piece2); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(piece1); f.add(piece2); f.setSize(500,500); f.setLocation(300,100); f.setVisible(true); } } class GraphicDragController extends MouseInputAdapter { GraphicDragAndDrop component; Point offset = new Point(); boolean dragging = false; public GraphicDragController(GraphicDragAndDrop gdad) { component = gdad; component.addMouseListener(this); component.addMouseMotionListener(this); } public void mousePressed(MouseEvent e) { Point p = e.getPoint(); Rectangle r = component.rect; if(r.contains(p)) { offset.x = p.x - r.x; offset.y = p.y - r.y; dragging = true; } } public void mouseReleased(MouseEvent e) { dragging = false; } public void mouseDragged(MouseEvent e) { if(dragging) { int x = e.getX() - offset.x; int y = e.getY() - offset.y; component.setRect(x, y); } } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.