我创建了一个扩展JPanel的 Hexagon 组件。它在PaintComponent()中绘制一个六边形多边形。为了让它用给定的颜色填充多边形,我创建了一个使组件重新绘制的Highlight()方法:
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();
}
}
现在,当我想一次突出显示(填充)许多六边形时,就会出现问题。为了突出显示它们,我将使用 for 循环并调用 Hexagon.highlight(Color.orange)。但是,对于用户来说,一次填充一个六边形是很明显的。这是填充过程的示例图像
我尝试了另一种重绘方式,让包含六边形的 JPanel 自行重绘它。例子:
// 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();
}
这没有用。知道如何一次填充所有六边形吗?谢谢。