gpt4 book ai didi

java - 平移时创建无限网格

转载 作者:行者123 更新时间:2023-11-30 06:44:02 25 4
gpt4 key购买 nike

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

我将如何绘制新区域并重新绘制?当我覆盖 paintComponent(...) 时,我通过循环遍历窗口中的 x 和 y 空间并每 10 使用 g.drawLine(...) 来创建网格单位。基于此example ,我在扩展 JPanelDrawing 类的构造函数中使用 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

关于java - 平移时创建无限网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43958092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com