JPanel grid issue
Ok, I am implementing a flowchart editor in Java. My goal is to provide a possibility to display grid lines on a drawing surface. I partially made it to work:
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
// Scrolling
g2.transform(transformation);
// Step one: draw grid
if(showGrid)
{
// Horizontal grid lines
for(int i = -1; i < getSize().getWidth(); i += 50)
{
g2.drawLine(i, 0, i, (int)getSize().getHeight());
}
// Vertical grid lines
for(int i = -1; i < getSize().getHeight(); i += 50)
{
g2.draw开发者_运维百科Line(0, i, (int)getSize().getWidth(), i);
}
}
// Step two: draw symbols
// ...
}
The results are like this:
But, if I scroll the diagram down or up, I get this:
As seen, diagram is scrolled, but not the grid. I also tried putting Step one code before g2.transform(transformation) line, but after that, if I scroll, grid lines are not moving.
So, the question is: is there a way to draw grid lines and avoid mentioned behavior? The goal is to scroll grid along with other elements on diagram.
- List item
The grid is being scrolled, but the lines do not extend to the new bounds.
The grid is scrolled along with the objects. That's why there's empty space at the bottom of the second diagram. The top of the grid has been scrolled off the top of the panel. The bottom of the grid has been scrolled above the bottom of the panel. The grid lines have moved.
The only problem I see is that the grid lines should always extend to the extents of the visible area. To do this, you need to reverse the transformation for the getWidth and getHeight and then draw the grid lines on all of the multiples of 50 between those values.
Paint the entire diagram and put it into a JScrollPane instead of transforming scroll actions yourself.
精彩评论