Updating stroke size dynamically for array of shapes in Java

197 views Asked by At

i have created a simple program in Java for painting Graphic primitives (Lines,Rectangles,Ellipses,etc.).The shapes are drawn on the screen with dragging the mouse and stored into an array of Shapes,so i have added a slider for getting the stroke size (from 1 to 20 with 1 being default value) dynamically,but it updates all the shapes that are previously drawn as well.

//NOTE1: Graphics2D graph; is defined in the class extending JFrame

//NOTE2: strokeSize value is dynamically changing with the slider

public void paint(Graphics g)
            {

                    graph = (Graphics2D)g;

                    graph.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);

                    graph.setStroke(new BasicStroke(strokeSize));

for (Shape currentShape : shapes)
                    {
                        graph.setPaint(strokeCounter.next());

                        graph.draw(currentShape);

                        graph.setPaint(fillCounter.next());

                        graph.fill(currentShape);
                    }


//What follows are If statements for choosing a shape 

//and actual methods for drawing them...

So my question is:How to update the strokeSize,but only for shapes currently being drawn?

2

There are 2 answers

3
Tim B On

Store the stroke size along with the shape. Set the stroke size before issuing the draw command.

2
Mohammad Banisaeid On

Add graph.setStroke(new BasicStroke(currentShape.getStrokeSize())); before graph.draw(currentShape);

You'll need to add a property called StrokeSize to your Shape class.