Reputation: 31
I have to following situation:
A JPanel
is used a "drawing board" where the user can add blocks that have specific connection points which can be used to interconnect to other blocks (think Simulink or labView).
The blocks themselves are JPanel
objects with buttons on them, that are added to the drawing board by the add() method after setting a null layout. The JPanels
can be dragged around with the help of a MouseMotionListener
.
To draw the connections, I override the drawing board paintComponent()
method and call g.drawLine() (after a call to super.paintComponent
). This works, but as soon as you move a block, the lines overlap each other and it turns into a mess.
Therefore I call drawingBoard.repaint()
during the time a user moves a block. This has the effect that the lines are flickering visible during dragging and then disappear immediately.
Clearly, the drawing of the JPanels
in the parent JPanel
interferes with each other.
How can I solve this?
edit: Some snippets of the code:
The drawing board:
public void paintComponent(Graphics g){
g.clearRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
drawConnections(g);//Contains g.drawLine calls
}
The blocks are added to the drawing board with the JPanel.add() method. Below is the MouseMotionListener of such a "block" JPanel.
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();
}
The block JPanel does not override paintComponent because no special drawing is necessary in it. It just contains some JLabels and JButtons. The buttons are used to create connections between blocks. The connection list is then used inside drawConnections mentioned above.
There's really not much more than this.
Ok, as expected this was a very small detail.
In the line drawing code I used
Graphics2D g2 = (Graphics2D) this.getGraphics();
instead of
Graphics2D g2 = (Graphics2D) g;
I just noticed the references are not the same. D'oh
Upvotes: 3
Views: 644
Reputation: 205785
If JDesktopPane
is an acceptable "drawing board," you could try the approach shown here.
Upvotes: 1
Reputation: 23629
On approach might be to make the lines be JComponents that have been added to the panel and having them repaint themselves. This might also have the nice effect of isolating the line logic and paint calculation in a line class instead of having it on your drawing board.
Upvotes: 2