平移时创建无限网格

Create an endless grid while panning

我正在编写一个具有 "Drawing area" 用户放置组件的应用程序。绘图区域包含一个组件将捕捉到的网格,但是当我调整 window 等的大小时它工作正常 ;但是当我平移该区域时,网格不会自行重绘。

我将如何着手绘制新区域并重新绘制?当我通过循环 window 中的 x 和 y space 并每 10 个单位使用 g.drawLine(...) 来覆盖 paintComponent(...) 时,我创建了网格。基于此 example,我在扩展 JPanel.

Drawing class 的构造函数中使用 MouseMotionListener 进行平移
public final class Drawing extends JPanel {

    private int spacing;
    private Point origin = new Point(0,0);
    private Point mousePt;

    /**
     * Default Constructor for Drawing Object. Calls JPanel default constructor.
     */
    public Drawing() {
        super();

        spacing = 10;
        setBackground(new Color(255, 255, 255));
        setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0)));

        GroupLayout workspacePanelLayout = new GroupLayout(this);
        setLayout(workspacePanelLayout);
        workspacePanelLayout.setHorizontalGroup(workspacePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 343, Short.MAX_VALUE));
        workspacePanelLayout.setVerticalGroup(workspacePanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 400, Short.MAX_VALUE));

        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent evt) {
                // this stuff is mainly for debugging....
                mousePt = evt.getPoint();
                System.out.println((mousePt.x - origin.x) + "," + (mousePt.y - origin.
                System.out.println(origin.x + ", " + origin.y);
            }
        });
        this.addMouseMotionListener(new MouseMotionAdapter() {
            //this is what is more important.
            @Override
            public void mouseDragged(MouseEvent evt) {
                if (evt.getButton() == MouseEvent.BUTTON2 || xorlogic.Window.cursorState == 1) {
                    int dx = evt.getX() - mousePt.x;
                    int dy = evt.getY() - mousePt.y;
                    origin.setLocation(origin.x+dx, origin.y+dy);
                    mousePt = evt.getPoint();
                    repaint();
                }
            }
        });
    }

以及后面实现的paintComponent(...):

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawLine(0, origin.y, getWidth(), origin.y);
    g.drawLine(origin.x, 0, origin.x, getHeight());
    // set up grid
    int x = 0;
    int y = 0;
    g.setColor(new Color(220, 220, 220));
    while (x < getWidth()) {
        g.drawLine(origin.x + x, 0, origin.x + x, getHeight());
        x += getSpacing();
    }
    while (y < getHeight()) {
        g.drawLine(0, origin.y + y, getWidth(), origin.y + y);
        y += getSpacing();
    }
}

非常感谢您的帮助。谢谢!

平移的最佳方式是使用 Graphics2D.scale,这样您就可以 (a) 避免 paintComponent 中的复杂逻辑,以及 (b) 使平移成为可重复使用的功能,如此处所示

https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/ui/drag/Zoomable.java#l58