You need to create a new Rectangle object on mousePressed and then assign it to the rectangle variable. Then you can change its state in the mouseDragged method.
Or better, use Point objects that are set on mouse events:
i.e.
// variable declarations
Point initialPoint = null;
Rectangle rectangle = null;
@Override
public void mousePressed(MouseEvent mEvt) {
initialPoint = mEvt.getPoint();
rectangle = null;
repaint();
}
mouseDragged(MouseEvent mEvt) {
// use initialPoint, mEvt.getPoint(),
// Math.abs(...), Math.min(...), and Math.max(...)
// to calculate x, y, w, and h
rectangle = new Rectangle(x, y, w, h);
repaint();
}
also in the paintComponent, only draw rectangle if it's not null.
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (rectangle != null) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
g2.fill(rectangle);
}
}
As for,
As of right now I am only trying to draw 1 rectangle but in the end the program will need to draw multiple rectangles so any help in that regard would be great.
This is easy. Create an ArrayList<Rectangle>
, and on mouseReleased place the created Rectangle object into the List. In the paintComponent method, iterate through the list with a for loop, drawing each Rectangle that it contains.