【发布时间】:2017-10-12 23:24:37
【问题描述】:
我正在编写一个应用程序,它有一个“绘图区域”,用户可以在其中放置组件。绘图区域包含组件将捕捉到的网格,但是当我调整窗口大小等时它工作正常 ;但是当我平移该区域时,网格不会自行重绘。
我将如何绘制新区域并重新绘制?当我通过遍历窗口中的 x 和 y 空间并每 10 个单位使用 g.drawLine(...) 来覆盖 paintComponent(...) 时,我创建了网格。基于这个example,我在扩展JPanel的Drawing类的构造函数中使用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();
}
}
非常感谢您的帮助。谢谢!
【问题讨论】:
标签: java swing user-interface paintcomponent