Good day! I am writing a program similar to MSPaint for the project. Here is the link to the repository with the full project -> https://github.com/ALazyGuy/LTP/tree/master/com/LTP/Paint . The bottom line is this: now add a drawing of a rectangle. Here is what it is:

package com.LTP.Paint; import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JPanel; import com.LTP.Paint.objects.Tools; public class Paint extends JPanel { public static Tools tool = Tools.PEN; public static Color selectedColor = Color.YELLOW; public static Color temp = selectedColor; public static int size = 2; public Paint(){ setSize(800, 600); addMouseListener(new Listener(this)); addMouseMotionListener(new Listener(this)); grabFocus(); } protected void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.WHITE); g.fillRect(0, 0, 800, 600); } } class Listener implements MouseListener, MouseMotionListener{ private Paint paint; public Listener(Paint paint){ this.paint = paint; } public void mouseDragged(MouseEvent e) { mouseClicked(e); } public void mouseClicked(MouseEvent e) { if((Paint.tool == Tools.PEN)){ Graphics g = paint.getGraphics(); g.setColor(Paint.selectedColor); g.fillRect((int)(e.getX() - (Paint.size / 2)), (int)(e.getY() - (Paint.size / 2)), Paint.size, Paint.size); } } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseMoved(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } 

I want to implement the drawing like this:

1) Add int x, y variables to the Listener class.

2) The mousePressed method is implemented like this:

 public void mousePressed(MouseEvent e){ x = e.getX(); y = e.getY(); /* А тут каким-то на данный момент неизвесным мне способом, сохранить текущее состояние моей панели. Так, что бы потом, я мог просто нарисавать это состояние. Например в переменной BufferedImage добавленной в классе Listener.*/ } 

3) The mouseDragged method is implemented like this:

 public void mouseDragged(MouseEvent e){ if(Paint.tool == Tools.RECTANGLE){ //На месте этого коментария рисую то сохраненное состояние на панели Graphics g = paint.getGraphics(); g.setColor(Paint.selectedColor); g.fillRect(x, y, e.getX() - x, e.getY() - y); } } 

4) The mouseReleased method is implemented in the same way as the mouseDragged method, but I do not draw the state of the panel.

Attention question! How to save and then draw this "State"?

  • Do you know anything about the MVC pattern? - Mikhail Vaysman
  • Unfortunately no. The first time I've heard. - Razor
  • I recommend to study. You will need it in this project. - Mikhail Vaysman
  • With the decision of this task or in general? - Razor
  • for this task very well suited. and for all tasks related to the GUI. - Mikhail Vaysman

0