I'm writing a program that displays a GUI with two rectangles ... upon clicking inside the area of either rectangle, the user should be able to drag the rectangle wherever they like, during which time, the color of the rectangle should change - but it should go back to its original color upon declicking. I can get my rectangle to move, but I cannot get it to change color. What should I do?
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ColorPanel extends JPanel{ private Rectangle r1, r2, r3; private Rectangle selectedRectangle; // Used to track selected shape private int x, y ; // Used to track mouse coordinates public ColorPanel(Color backColor){ setBackground(backColor); r1 = new Rectangle(5, 5, 25, 25, Color.red); r2 = new Rectangle(50, 50, 25, 25, Color.blue); selectedRectangle = null; addMouseListener(new PanelListener()); addMouseMotionListener(new PanelMotionListener()); } public void paintComponent(Graphics g){ super.paintComponent(g); if (selectedRectangle == null) r1.fill(g); r2.fill(g); } private class PanelListener extends MouseAdapter{ public void mousePressed(MouseEvent e){ x = e.getX(); y = e.getY(); if (r1.containsPoint(x, y)){ selectedRectangle = r1; } else if (r2.containsPoint(x, y)){ selectedRectangle = r2; } } public void mouseReleased(MouseEvent e){ x = e.getX(); y = e.getY(); selectedRectangle = null; } } private class PanelMotionListener extends MouseMotionAdapter{ public void mouseDragged(MouseEvent e){ int newX = e.getX(); int newY = e.getY(); int dx = newX - x; int dy = newY - y; if (selectedRectangle == r1){ selectedRectangle.move(dx, dy); x = newX; y = newY; repaint(); } } } }