Question: I have this code in JAVA that draws a rectangle like the paint app when I drag my mouse on the panel. Every time I
I have this code in JAVA that draws a rectangle like the paint app when I drag my mouse on the panel. Every time I click and drag to make a new rectangle, the previous one disappears. I was wondering if there is a way for it to stay on the panel. And for there to be multiple rectangles, just like the paint app on windows.
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DrawRect extends JPanel { int x, y, x2, y2; public static void main(String[] args) { JFrame f = new JFrame("Draw Box Mouse 2"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setContentPane(new DrawRect()); f.setSize(300, 300); f.setVisible(true); } DrawRect() { x = y = x2 = y2 = 0; // MyMouseListener listener = new MyMouseListener(); addMouseListener(listener); addMouseMotionListener(listener); } public void setStartPoint(int x, int y) { this.x = x; this.y = y; } public void setEndPoint(int x, int y) { x2 = (x); y2 = (y); }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
