不久前我在这里问过类似的问题,但没有得到答案。最初的问题是关于单击形状后更改形状的颜色。但是我对绘制后如何访问形状感到困惑。
这是我的paintComponent 方法
@Override
protected void paintComponent(Graphics graph) {
super.paintComponent(graph);
Graphics2D g = (Graphics2D) graph;
// smooth graphics
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// moving to the middle of the panel
g.translate(this.getWidth()/2, this.getHeight()/2);
// painting colored arcs
for(int i = 0; i < 4; i++) {
g.setColor(dimColors[i]);
g.fill(arcs[i]);
}
// painting borders
g.setColor(Color.BLACK);
g.setStroke(new BasicStroke(5F));
g.drawLine(-98, 0, 98, 0);
g.drawLine(0, -98, 0, 98);
g.draw(circle);
// painting central white circle
g.setColor(Color.WHITE);
g.fill(smallCircle);
g.setColor(Color.BLACK);
g.draw(smallCircle);
}
arcs[] 数组包含一组绘制在面板上的 Arc2D。我现在的问题是,如果我想改变例如 arcs[0] 的颜色,我该怎么做?
谢谢!
编辑:我现在有这个 MouseAdapter 事件
private class MyMouseAdapter extends MouseAdapter {
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
Component c = getComponentAt(p);
Graphics g = c.getGraphics();
dimColors[1] = Color.RED;
paintComponent(g);
}
}
它起作用了,它改变了 arc[1] 的颜色,因为 arcs[1] 在绘制它时将 dimColors[1] 设置为颜色。
但是,我仍然不知道如何检查是否单击了正确的弧。现在您只需单击图形面板上的任意位置,它就会更改该特定弧的颜色