Reputation: 155
I have created a Hexagon component that extends JPanel. It draws a hexagon polygon in PaintComponent(). To make it fill the polygon with a given color, I created a Highlight() method that causes the component to repaint:
public class Hexagon{
private Color highlightColor;
private boolean highlighted;
private Polygon polygon;
public Hexagon(int width ... etc){
// code to create the hexagon polygon to be drawn
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawPolygon(polygon);
// highlighting
if(highlighted){
g2d.setColor(highlightColor);
g2d.fillPolygon(polygon);
}
}
public void highlight(Color highlightColor){
highlight(highlightColor, false);
}
public void highlight(Color highlightColor, boolean dontRepaint){
highlighted = true;
this.highlightColor = highlightColor;
if(dontRepaint) { return; }
repaint();
}
}
Now, the problem occurs when I want to highlight (fill) many hexagons at once. To highlight them I will use a for loop and call Hexagon.highlight(Color.orange). However, It will be obvious for the user that one hexagon is being filled at a time. Here is a sample image of how the filling takes place
I tried another way of repaint by letting the containing JPanel that contains the Hexagons to repaint it self. Example:
// this code is inside the containing Jpanel that hosts all the hexagons
public void highlightManyHexagons(List<Hexagon> hexes){
for(Hexagon h : hexes){
// use overload that prevents the hexagon to do a repaint
h.highlight(Color.orange, true);
}
// repaint the whole panel
repaint();
}
This didn't work. Any idea how to make all the hexagons to be filled at once? Thanks.
Upvotes: 1
Views: 1362
Reputation: 1202
Try using setIgnoreRepaint
, it will hold "unwelcome" paint events.
See the Java documentation of Component.setIgnoreRepaint(boolean):
Sets whether or not paint messages received from the operating system should be ignored. This does not affect paint events generated in software by the AWT, unless they are an immediate response to an OS-level paint message.
This is useful, for example, if running under full-screen mode and better performance is desired, or if page-flipping is used as the buffer strategy.
Upvotes: 1
Reputation: 57421
You can try to create one Shape consisting from all the hexagons to be filled.
Use Area
class and public void add(Area rhs)
method. Area can be created based on Hexagon Shape object.
Then fill the single area.
Upvotes: 1