我有一个在JPanel上绘制的Shape列表,我需要更改那些包含通过鼠标点击获得的点的颜色,但我真的不能理解如何使用repaint()来做到这一点。
这是测试类:
public class TestShapeViewer
{
public static void main(String[] args)
{
List<Shape> figure = new ArrayList<Shape>();
Utils util = new Utils();
figure.add(new Rect(new P2d(200,200), new P2d(90,40)));
figure.add(new Circle(new P2d (150,150), new P2d (300,150)));
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowWindow(figure);
}
});
}
private static void createAndShowWindow(List<Shape> figure)
{
JFrame window = new JFrame("TestShapeViewer");
window.setSize(500,500);
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(new Viewer(figure));
window.pack();
window.setVisible(true);
}
}
这是我的JPanel类
public class Viewer extends JPanel implements ShapeViewer
{
private List<Shape> shapesToDraw;
private List<Shape> shapeToColor;
private Utils utility = new Utils();
private Color colorToUse;
public Viewer(List<Shape> shapes)
{
this.shapesToDraw = shapes;
this.colorToUse = Color.BLACK;
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
repaintShapes(e.getX(), e.getY());
}
});
}
public void update(List<Shape> shapes)
{
this.shapesToDraw = shapes;
}
public Dimension getPreferredSize()
{
return new Dimension(500,500);
}
public void paintComponent(Graphics shape)
{
super.paintComponent(shape);
shape.setColor(colorToUse);
shapesToDraw.stream().forEach(x -> DrawShape(shape,x));
}
public void DrawShape(Graphics shape, Shape s)
{
BBox box = s.getBBox();
if (s instanceof Line)
{
shape.drawLine(box.getUpperLeft().getX(),
box.getUpperLeft().getY(),
box.getBottomRight().getX(),
box.getBottomRight().getY());
}
else if(s instanceof Rect)
{
int[] xpoints = {box.getUpperLeft().getX(),
box.getBottomRight().getX(),
box.getBottomRight().getX(),
box.getUpperLeft().getX()};
int[] ypoints = {box.getUpperLeft().getY(),
box.getUpperLeft().getY(),
box.getBottomRight().getY(),
box.getBottomRight().getY()};
Polygon rect = new Polygon(xpoints, ypoints, 4);
shape.drawPolygon(rect);
}
else if(s instanceof Circle)
{
int raggio = (int)(new Line(box.getUpperLeft(),
new P2d(box.getBottomRight().getX(),
box.getUpperLeft().getY())).getPerim())/2;
shape.drawOval(box.getUpperLeft().getX(),
box.getUpperLeft().getY(),
raggio*2, raggio*2);
}
else if(s instanceof Combo)
{
Combo co = (Combo) s;
co.getComp().stream().forEach(x -> DrawShape(shape,x));
}
}
private void repaintShapes(int x, int y)
{
shapeToColor = utility.getContaining(shapesToDraw,new P2d(x,y));
this.colorToUse = Color.RED;
repaint();
}
}
我的目的是点击一个点,检查哪些形状包含该点并仅改变它们的颜色。
为清楚起见:
答案 0 :(得分:1)
我有一个在JPanel上绘制的Shape列表,我需要更改包含点的那些颜色
而不是保持形状列表。您可以保留“ColoredShapes”列表。您将创建一个包含两个属性的自定义类:1)Shape,2)Color并将此对象添加到List。当然,在绘制Shape之前,您还需要修改绘制代码以获取Color信息。
然后,当您使用鼠标单击迭代List的点以查找包含鼠标点的任何Shape并更新Color时。然后,您只需在自定义绘图面板上调用repaint()。
查看Custom Painting Approaches中的DrawOnComponent
示例。这种方法使用“ColoredRectangle”来跟踪这两个属性,因此该方法与您需要的方法非常相似。