平移时创建无限网格

时间:2017-05-13 21:19:58

标签: java swing user-interface paintcomponent

我正在编写一个具有“绘图区域”的应用程序,用户可以在其中放置组件。绘图区域包含组件将捕捉到的网格,但是当我调整窗口大小等时它可以正常工作 enter image description here;但是当我平移该区域时,网格不会重绘。 enter image description here

我将如何绘制新区域并重新绘制?我通过循环遍历窗口中的x和y空格并每10个单位使用paintComponent(...)来覆盖g.drawLine(...)时创建网格。基于此example,我在MouseMotionListener类的构造函数中使用Drawing进行平移,扩展JPanel

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();
    }
}

我非常感谢你的帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

平移的最佳方法是使用Graphics2D.scale,这样你可以(a)避免paintComponent中的复杂逻辑和(b)平移可重用的功能,如下所示

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