I'm trying to create a canvas(JPanel) that can have text Boxes(JTextArea) on it and I can also drag the canvas or the text boxes around. Now the dragging text boxes functions are ok. I can use setBounds() to set the location for the JTextArea.
However, when it comes to dragging the canvas, problems come. I use Graphics2D.transform to move the canvas. After the canvas is moving, there will be a visual text area and a hidden real text area. I have reset the bounds of JTextArea to fit the moving offset of the canvas but it doesn't work.
Below is an example,

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.AffineTransform;
/**
* @author Zhijie Lan<p>
* create date: 2020/11/25<p>
**/
public class TranslateJPanel extends JFrame
{
public TranslateJPanel() throws HeadlessException
{
Canvas canvas = new Canvas();
add(canvas,BorderLayout.CENTER);
this.setSize(1280, 720);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args)
{
new TranslateJPanel();
}
}
class Canvas extends JPanel
{
private final JTextArea jTextArea;
private int offset = 0;
public Canvas()
{
setLayout(null);
jTextArea = new JTextArea("hello!!!!!!!!!!!");
jTextArea.setBounds(0,0,100,100);
jTextArea.setBorder(BorderFactory.createLineBorder(Color.BLACK));
add(jTextArea);
this.addMouseMotionListener(new MouseMotionAdapter()
{
@Override
public void mouseDragged(MouseEvent e)
{
super.mouseDragged(e);
offset++;
revalidate();
repaint();
}
});
this.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e)
{
super.mouseClicked(e);
System.out.println("M: "+ e.getX()+" "+e.getY());
}
});
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
AffineTransform at = new AffineTransform();
at.translate(offset, offset);
g2.transform(at);
jTextArea.setBounds(offset,offset,100,100);
System.out.println(offset);
System.out.println(jTextArea.getX()+" "+jTextArea.getY());
System.out.println("***************************");
}
}