Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Size of stroke is updating for all shapes in array.Why?

  1. #1
    Junior Member
    Join Date
    Dec 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Size of stroke is updating for all shapes in array.Why?

    Hello everyone,
    i have a problem with the code below.Basically what we have is a simple program for drawing shapes (line,rectangle,ellipse) and the issue i have is that the stroke size is updating dynamically for all the shapes that are drawn (added to the Shapes array) and not only for the current shape being drawn.

    If you draw a line for example with stroke size 2 and then draw another line with say stroke size 6 both lines will update to stroke size 6 instead of just the second line.This is valid for all the other shapes as well.

    The following line: graphSettings.setStroke(new BasicStroke(strokeparentVal));

    sets the stroke size from the strokeparentVal which can be dynamically changed with the slider.

    So,i want to change the stroke size only for the shape currently being drawn.Will appreciate any help!

    import javax.swing.*;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
     
    import java.awt.event.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.util.*;
     
    public class PaintExample extends JFrame
    {
     
    		JButton brushBut, lineBut, ellipseBut, rectBut, strokeBut, fillBut;
     
    		Graphics2D graphSettings;
     
    		int currentAction = 1;
     
    		Color strokeColor=Color.BLACK, fillColor=Color.BLACK;
     
    		JSlider strokeSlider;
     
    		JLabel strokeLabel;
     
    		public float strokeparentVal =1;
     
            public static void main(String [] args)
            {
                    new PaintExample();
            }
     
            public PaintExample()
            {
     
                this.setSize(800, 600);
                this.setTitle("Java Paint");
                this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
                JPanel buttonPanel = new JPanel(); 
     
                Box theBox = Box.createHorizontalBox();
     
                brushBut = makeMeButtons("./src/brush.png", 1);
                lineBut = makeMeButtons("./src/Line.png", 2);
                ellipseBut = makeMeButtons("./src/Ellipse.png", 3);
                rectBut = makeMeButtons("./src/Rectangle.png", 4);  
     
                strokeBut = makeMeColorButton("./src/Stroke.png", 5, true);
                fillBut = makeMeColorButton("./src/Fill.png", 6, false);
     
                theBox.add(brushBut);
                theBox.add(lineBut);
                theBox.add(ellipseBut);
                theBox.add(rectBut);
                theBox.add(strokeBut);
                theBox.add(fillBut); 
     
                strokeLabel = new JLabel("Stroke: 1");
     
                strokeSlider = new JSlider(1,25,1);
     
                ListenForSlider sForSlider = new ListenForSlider();
     
                theBox.add(strokeLabel);
                theBox.add(strokeSlider);
     
                strokeSlider.addChangeListener(sForSlider);
     
                buttonPanel.add(theBox);
     
                this.add(buttonPanel, BorderLayout.SOUTH);
     
                this.add(new DrawingBoard(), BorderLayout.CENTER);
     
                this.setVisible(true);
            } 
     
            public JButton makeMeButtons(String iconFile, final int actionNum){
            	JButton theBut = new JButton();
                Icon butIcon = new ImageIcon(iconFile);
                theBut.setIcon(butIcon);
     
                theBut.addActionListener(new ActionListener() {
     
    				public void actionPerformed(ActionEvent e) {
    					currentAction = actionNum;
     
    				}
                });
     
                return theBut;  
            }
     
            public JButton makeMeColorButton(String iconFile, final int actionNum, final boolean stroke){
            	JButton theBut = new JButton();
                Icon butIcon = new ImageIcon(iconFile);
                theBut.setIcon(butIcon);
     
                theBut.addActionListener(new ActionListener() {
     
    				public void actionPerformed(ActionEvent e) {
     
    					if(stroke){
     
    						strokeColor = JColorChooser.showDialog(null,  "Pick a Stroke", Color.BLACK);
    					} else {
    						fillColor = JColorChooser.showDialog(null,  "Pick a Fill", Color.BLACK);
    					}
     
    				}
                });
     
                return theBut;  
            }
     
            private class DrawingBoard extends JComponent
            {
     
                    ArrayList<Shape> shapes = new ArrayList<Shape>();
                    ArrayList<Color> shapeFill = new ArrayList<Color>();
                    ArrayList<Color> shapeStroke = new ArrayList<Color>();
                    Point drawStart, drawEnd;
     
                    public DrawingBoard()
                    {
     
                            this.addMouseListener(new MouseAdapter()
                              {
     
                                public void mousePressed(MouseEvent e)
                                {
     
                                	if(currentAction != 1){
     
                                	drawStart = new Point(e.getX(), e.getY());
                                	drawEnd = drawStart;
                                    repaint();
     
                                	}
     
     
                                    }
     
                                public void mouseReleased(MouseEvent e)
                                    {
     
                                	if(currentAction != 1){
     
                                	Shape aShape = null;
     
                                	if (currentAction == 2){
                                		aShape = drawLine(drawStart.x, drawStart.y,
                                				e.getX(), e.getY());
                                	} else 
     
                                	if (currentAction == 3){
                                		aShape = drawEllipse(drawStart.x, drawStart.y,
                                				e.getX(), e.getY());
                                	} else 
     
                                	if (currentAction == 4) {
     
                                        aShape = drawRectangle(drawStart.x, drawStart.y,
                                        		e.getX(), e.getY());
                                	}
     
     
                                      shapes.add(aShape);
                                      shapeFill.add(fillColor);
                                      shapeStroke.add(strokeColor);
     
                                      drawStart = null;
                                      drawEnd = null;
     
                                      repaint();
     
                                	}
                                    }
                              } );
     
                            this.addMouseMotionListener(new MouseMotionAdapter()
                            {
     
                              public void mouseDragged(MouseEvent e)
                              {
     
                            	  if(currentAction == 1){
     
                          			int x = e.getX();
                          			int y = e.getY();
     
                          			Shape aShape = null;
     
                          			strokeColor = fillColor;
     
                          			aShape = drawBrush(x,y,5,5);
     
                          			  shapes.add(aShape);
                                      shapeFill.add(fillColor);
                                      shapeStroke.add(strokeColor);
     
                          		} 
     
                            	drawEnd = new Point(e.getX(), e.getY());
                                repaint();
                              }
                            } );
                    }
     
     
                    public void paint(Graphics g)
                    {
     
                            graphSettings = (Graphics2D)g;
     
                            graphSettings.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                    RenderingHints.VALUE_ANTIALIAS_ON);
     
                            Iterator<Color> strokeCounter = shapeStroke.iterator();
                            Iterator<Color> fillCounter = shapeFill.iterator();
     
                            for (Shape s : shapes)
                            {
     
                            	graphSettings.setPaint(strokeCounter.next());
                            	graphSettings.setStroke(new BasicStroke(strokeparentVal));
                            	graphSettings.draw(s);
     
                            	graphSettings.setPaint(fillCounter.next());
     
                            	graphSettings.fill(s);
                            }
     
                            if (drawStart != null && drawEnd != null)
                            {
     
                                graphSettings.setComposite(AlphaComposite.getInstance(
                                        AlphaComposite.SRC_OVER, 0.40f));
     
                            	graphSettings.setPaint(Color.LIGHT_GRAY);
     
                            	Shape aShape = null;
     
                            	if (currentAction == 2){
                            		aShape = drawLine(drawStart.x, drawStart.y,
                                    		drawEnd.x, drawEnd.y);
                            	} else 
     
                            	if (currentAction == 3){
                            		aShape = drawEllipse(drawStart.x, drawStart.y,
                                    		drawEnd.x, drawEnd.y);
                            	} else 
     
                            	if (currentAction == 4) {
     
                                    aShape = drawRectangle(drawStart.x, drawStart.y,
                                    		drawEnd.x, drawEnd.y);
                            	}
     
     
                                    graphSettings.draw(aShape);
                            }
                    }
     
                    private Rectangle2D.Float drawRectangle(
                            int x1, int y1, int x2, int y2)
                    {
     
                            int x = Math.min(x1, x2);
                            int y = Math.min(y1, y2);
     
     
                            int width = Math.abs(x1 - x2);
                            int height = Math.abs(y1 - y2);
     
                            return new Rectangle2D.Float(
                                    x, y, width, height);
                    }
     
     
                    private Ellipse2D.Float drawEllipse(
                            int x1, int y1, int x2, int y2)
                    {
                            int x = Math.min(x1, x2);
                            int y = Math.min(y1, y2);
                            int width = Math.abs(x1 - x2);
                            int height = Math.abs(y1 - y2);
     
                            return new Ellipse2D.Float(
                                    x, y, width, height);
                    }
     
                    private Line2D.Float drawLine(
                            int x1, int y1, int x2, int y2)
                    {
     
                            return new Line2D.Float(
                                    x1, y1, x2, y2);
                    }
     
                    private Ellipse2D.Float drawBrush(
                            int x1, int y1, int brushStrokeWidth, int brushStrokeHeight)
                    {
     
                    	return new Ellipse2D.Float(
                                x1, y1, brushStrokeWidth, brushStrokeHeight);
     
                    }
     
            }
     
     
    private class ListenForSlider implements ChangeListener{
     
     
            	public void stateChanged(ChangeEvent e) {
     
            		if(e.getSource() == strokeSlider){
     
     
            			strokeLabel.setText("Stroke: " + strokeSlider.getValue() );
     
     
            			strokeparentVal = (float) (strokeSlider.getValue());
     
            		}
     
            	}
     
            }
    }


  2. #2
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Size of stroke is updating for all shapes in array.Why?

    Quote Originally Posted by exiz View Post
    i have a problem with the code below.Basically what we have is a simple program for drawing shapes (line,rectangle,ellipse) and the issue i have is that the stroke size is updating dynamically for all the shapes that are drawn (added to the Shapes array) and not only for the current shape being drawn.
    Firstly, a "design" issue you should understand. You have used 3 distinct collections:

                    ArrayList<Shape> shapes = new ArrayList<Shape>();
                    ArrayList<Color> shapeFill = new ArrayList<Color>();
                    ArrayList<Color> shapeStroke = new ArrayList<Color>();
    You should create a single class to "model" a shape plus all its features. Currently you are doing:

                            Iterator<Color> strokeCounter = shapeStroke.iterator();
                            Iterator<Color> fillCounter = shapeFill.iterator();
     
                            for (Shape s : shapes)
                            {
     
                            	graphSettings.setPaint(strokeCounter.next());
                            	graphSettings.setStroke(new BasicStroke(strokeparentVal));
                            	graphSettings.draw(s);
     
                            	graphSettings.setPaint(fillCounter.next());
     
                            	graphSettings.fill(s);
                            }
    Which is not only bad to see but may also be error-prone.


    Returning to the problem you have explained, it's easy: the "stroke" property of Graphics2D is set from strokeparentVal which is not a property of each figure but is a variable directly controller by the slider.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  3. #3
    Junior Member
    Join Date
    Dec 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Size of stroke is updating for all shapes in array.Why?

    So,
    for a better design i will have to create one main class that contains all the properties of the shapes such as inner color (shapefill),border color (strokefill) and stroke size and make all the other classes (shapes) inherit those properties from that base class.

    "Returning to the problem you have explained, it's easy: the "stroke" property of Graphics2D is set from strokeparentVal which is not a property of each figure but is a variable directly controller by the slider."

    Yeah,exactly.The problem is that every time there is call with new BasicStroke,so is there a way this to be fixed in the code the way it is right now ?

    Thanks!

  4. #4
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Size of stroke is updating for all shapes in array.Why?

    Quote Originally Posted by exiz View Post
    so is there a way this to be fixed in the code the way it is right now ?
    Keeping your current design, you should add a fourth collection, say for example ArrayList<Float> shapeStrokeWidth.
    But as you can guess, it is becoming a too much growing and complex design. Too many collections, iterators, etc....

    So please ..... redesign!
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

Similar Threads

  1. Java 1.4 Array issues - controlling array size for dynamic usage
    By doonan79 in forum Collections and Generics
    Replies: 5
    Last Post: June 18th, 2013, 11:53 AM
  2. compile errors when creating a 2nd array the same size as 1st array
    By javaiscool in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 26th, 2013, 09:35 PM
  3. Trouble Updating an Array
    By Gravity Games in forum Java Theory & Questions
    Replies: 36
    Last Post: July 25th, 2012, 12:52 AM
  4. Adding an array of shapes to a GUI window
    By cslx99 in forum AWT / Java Swing
    Replies: 3
    Last Post: December 8th, 2011, 06:03 AM
  5. Doubling The Array Size And Randomizing Array Return
    By Pingu00 in forum What's Wrong With My Code?
    Replies: 18
    Last Post: June 27th, 2011, 10:50 AM

Tags for this Thread