我必须以下情况:
AJPanel
用作“绘图板”,用户可以在其中添加具有特定连接点的模块,这些连接点可用于与其他模块互连(想想 Simulink 或 labView)。
块本身是JPanel
带有按钮的对象,在设置空布局后通过 add() 方法添加到绘图板上。JPanels
可以在 的帮助下拖动MouseMotionListener
。
为了绘制连接,我重写了绘图板paintComponent()
方法并调用 g.drawLine()(在调用 之后super.paintComponent
)。这行得通,但是一旦你移动一个块,线条就会相互重叠,就会变得一团糟。因此,我drawingBoard.repaint()
在用户移动块期间调用。这样做的效果是线条在拖动过程中闪烁可见,然后立即消失。
JPanels
显然,父级中的绘图JPanel
相互干扰。
我该如何解决这个问题?
编辑:一些代码片段:
绘图板:
public void paintComponent(Graphics g){
g.clearRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
drawConnections(g);//Contains g.drawLine calls
}
使用 JPanel.add() 方法将块添加到绘图板上。下面是这样一个“块”JPanel 的 MouseMotionListener。
public void mouseDragged(MouseEvent e)
{
pt = SwingUtilities.convertPoint(movingPanel, e.getX(), e.getY(), movingPanel.getParent());
movingPanel.setBounds(pt.x - clickX, pt.y - clickY, movingPanel.getWidth(), movingPanel.getHeight());
e.consume();
movingPanel.getParent().repaint();
}
块 JPanel 不会覆盖paintComponent,因为其中不需要特殊的绘图。它只包含一些 JLabels 和 JButton。这些按钮用于在块之间创建连接。然后在上面提到的 drawConnections 中使用连接列表。
真的没有比这更多的了。
解决了:
好的,正如预期的那样,这是一个非常小的细节。
在我使用的线条图代码中
Graphics2D g2 = (Graphics2D) this.getGraphics();
代替
Graphics2D g2 = (Graphics2D) g;
我只是注意到参考文献不一样。德欧