[英]java.awt.Graphics change color after drawing
我之前在这里问过类似的问题,但没有得到答案。 最初的问题是关于在单击形状后更改形状的颜色。 但是我对绘制后如何访问形状感到困惑。
这是我的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]设置为颜色。
但是,我仍然不知道如何检查是否单击了正确的弧。 现在,您只需单击图形面板上的任意位置,它就会更改该特定弧的颜色
这不会回答您先前的问题,但是会回答您的点击检测问题。 为此,最好使用Graphics2D,因为它比大多数其他选项更容易编写。 这是一个例子:
public class GraphicsPanel extends JPanel implements MouseListener
{
private Rectangle2D rect;
首先,我们创建Graphics2D矩形rect。
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)(g);
g2d.setColor(Color.GREEN);
rect = new Rectangle2D.Double(70, 70, 100, 100);
g2d.fill(rect);
this.addMouseListener(this);
}
然后,我们重写paintComponent方法并创建新的Rectangle2D.Double对象。 然后,我们用g2d.fill()填充矩形,然后向JPanel添加鼠标侦听器。
public void mousePressed(MouseEvent e)
{
if(rect.contains(e.getX(), e.getY()))
System.out.println("Rectangle clicked");
}
}
最后,我们需要查看该矩形是否包含用户单击的点。 为此,只需使用Rectangle2D.double的contains(int x,int y)方法查看我们创建的矩形是否包含用户的点击位置。 而已!
如果我想更改例如arcs [0]的颜色,该怎么做?
一条线(或其他任何东西)仅以一堆以原始颜色绘制的像素存在。 要更改其颜色,必须更改当前颜色并再次绘制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.