Results 1 to 13 of 13
  1. #1
    kaizen9001 is offline Member
    Join Date
    Mar 2011
    Posts
    13
    Rep Power
    0

    Default A bit of confusion with passing variables/infinite loop

    Hi all, I'm having a bit of a problem here...
    I'm making a simple MS Paint style program which allows the user to draw different shapes on a panel and edit the line thickness/width and the shape they'd like to draw using controls on a frame.
    I have my 3 classes, my frame(which includes my main method and user input buttons), my panel(for drawing on) and a class which holds all the variables of the shapes etc (I know this could probably go into the frame class, but I'll do that later)
    Anyway, the problem I'm having is that my frame class calls my panel in order to create a space to draw on, my panel calls the variables from my line variable class and my line variable class calls variables from my frame class (due to the user input on the frame). Then of course, the frame class calls the panel class again etc etc etc.
    Any ideas of how I can get out of this?
    Thanks!

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Before even creating any code, it's best to think this stuff through. When I've done similar type or projects, the MouseListeners get added to the JPanel that does the drawing, the JPanel that does the drawing usually doesn't need to call any methods on the containers that hold it but rather the containing classes will call public methods of the drawing JPanel for example to change the width of the lines, to change the shape it is supposed to draw, etc.

    If this doesn't help, you may need to post more information about your classes and actual code. An SSCCE would be the best code post to solve any specific problems you may be having but will take effort for you to create (but is worth it).

  3. #3
    Solarsonic is offline Senior Member
    Join Date
    Mar 2011
    Posts
    261
    Rep Power
    4

    Question

    Quote Originally Posted by kaizen9001 View Post
    Hi all, I'm having a bit of a problem here...
    I'm making a simple MS Paint style program which allows the user to draw different shapes on a panel and edit the line thickness/width and the shape they'd like to draw using controls on a frame.
    I have my 3 classes, my frame(which includes my main method and user input buttons), my panel(for drawing on) and a class which holds all the variables of the shapes etc (I know this could probably go into the frame class, but I'll do that later)
    Anyway, the problem I'm having is that my frame class calls my panel in order to create a space to draw on, my panel calls the variables from my line variable class and my line variable class calls variables from my frame class (due to the user input on the frame). Then of course, the frame class calls the panel class again etc etc etc.
    Any ideas of how I can get out of this?
    Thanks!
    As long as the variables are static, just reference them like so:
    Java Code:
    ClassName.staticVariable:
    If the variable isn't static, you'll need to create an instance of the class like so:
    Java Code:
    ClassName object = new ClassName(constructor):
    And then reference the object.

    An infinite loop is done like this:
    Java Code:
    for(; ;){}
    About not having to call so many variables, try having less classes and less variables than required.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Solarsonic View Post
    As long as the variables are static, just reference them like so:
    Java Code:
    ClassName.staticVariable:
    If the variable isn't static, you'll need to create an instance of the class like so:
    Java Code:
    ClassName object = new ClassName(constructor):
    And then reference the object.

    An infinite loop is done like this:
    Java Code:
    for(; ;){}
    About not having to call so many variables, try having less classes and less variables than required.

    Not sure how this helps the OP as his problems don't appear to be with how to refer to variables or the number of classes or variables, but rather that he has too many unnecessary communications between objects, with too tight a coupling between classes and a bad coupling between classes -- one that generates infinite loops.
    Last edited by Fubarable; 03-27-2011 at 08:12 PM.

  5. #5
    kaizen9001 is offline Member
    Join Date
    Mar 2011
    Posts
    13
    Rep Power
    0

    Default

    Here is an SSCCE (I think... the file size is a bit big...). Let me know if this isn't what you're looking for. SSCCE.zip

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Please read the SSCCE link which you'll find here: SSCCE

    It will explain all that we need and again will require effort on your part to create but will be well worth it both for you and for us. Your SSCCE code should be in one file and small enough to post the actual code here in this forum (using code tags).

  7. #7
    kaizen9001 is offline Member
    Join Date
    Mar 2011
    Posts
    13
    Rep Power
    0

    Default

    Ahh sorry, I had read through it, but clearly didn't understand. My mind is mush at the moment I'm afraid =(
    I'll try again:
    Java Code:
    package CM3063.cw1;
    
    import java.awt.Color;
    import javax.swing.JColorChooser;
    
    public class DrawFrame extends javax.swing.JFrame {
        private DrawPanel drawPanel;
        public int myLineWidth;
        public int toolChooser;
        public Color myLineColour;
    
    
        public DrawFrame() {
           drawPanel = new DrawPanel();
           getContentPane().add(drawPanel,java.awt.BorderLayout.CENTER);
           initComponents();
    
        }
        public void setMyLineWidth(int width) {
            myLineWidth = width;
        }
    
        public void setMyRadioButton(int tool) {
            toolChooser = tool;
        }
    
        public void setMyLineColour (Color colour) {
            myLineColour = colour;
        }
    
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            buttonGroup1 = new javax.swing.ButtonGroup();
            buttonGroup2 = new javax.swing.ButtonGroup();
            jPanel1 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jComboBox1 = new javax.swing.JComboBox();
            jPanel2 = new javax.swing.JPanel();
            jRadioButton1 = new javax.swing.JRadioButton();
            jRadioButton2 = new javax.swing.JRadioButton();
            jRadioButton3 = new javax.swing.JRadioButton();
            jRadioButton4 = new javax.swing.JRadioButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
            jPanel1.setLayout(new java.awt.GridLayout(2, 2, 12, 12));
    
            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
            jPanel1.add(jButton1);
    
            jButton2.setText("jButton2");
            jPanel1.add(jButton2);
    
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "4", "8", "16", "32" }));
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBox1ActionPerformed(evt);
                }
            });
            jPanel1.add(jComboBox1);
    
            jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
            jPanel2.setLayout(new java.awt.GridLayout(1, 5, 4, 4));
    
            buttonGroup1.add(jRadioButton1);
            jRadioButton1.setText("jRadioButton1");
            jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jRadioButton1ActionPerformed(evt);
                }
            });
            jPanel2.add(jRadioButton1);
    
            buttonGroup1.add(jRadioButton2);
            jRadioButton2.setText("jRadioButton2");
            jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jRadioButton2ActionPerformed(evt);
                }
            });
            jPanel2.add(jRadioButton2);
    
            buttonGroup1.add(jRadioButton3);
            jRadioButton3.setText("jRadioButton3");
            jRadioButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jRadioButton3ActionPerformed(evt);
                }
            });
            jPanel2.add(jRadioButton3);
    
            buttonGroup1.add(jRadioButton4);
            jRadioButton4.setText("jRadioButton4");
            jRadioButton4.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jRadioButton4ActionPerformed(evt);
                }
            });
            jPanel2.add(jRadioButton4);
    
            jPanel1.add(jPanel2);
    
            getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_START);
    
            pack();
        }// </editor-fold>                        
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            Color colourChosen =  JColorChooser.showDialog(
                    this, "Choose colors", Color.green);
            myLineColour = (colourChosen);
        }                                        
    
    
        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
            String myLineWidth = (String)jComboBox1.getSelectedItem();
            System.out.println(myLineWidth);
        }                                          
    
    
        private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                              
            toolChooser = 1;
        }                                             
    
        private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                              
            toolChooser = 2;
        }                                                                                
    
    
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new DrawFrame().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify                     
        private javax.swing.ButtonGroup buttonGroup1;
        private javax.swing.ButtonGroup buttonGroup2;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JRadioButton jRadioButton1;
        private javax.swing.JRadioButton jRadioButton2;
        private javax.swing.JRadioButton jRadioButton3;
        private javax.swing.JRadioButton jRadioButton4;
        // End of variables declaration                   
    
    }
    
    
    
    
    
    
    
    
    
    
    
    
    package CM3063.cw1;
    
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Shape;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Line2D;
    import java.awt.geom.QuadCurve2D;
    import java.awt.geom.RoundRectangle2D;
    import java.awt.image.BufferedImage;
    
    
    public class DrawPanel extends javax.swing.JPanel {
    
        private int xStart = 0;
        private int yStart = 0;
        private int xEnd, yEnd;
        private int xOld = 0;
        private int yOld = 0;
        private boolean drawing = false;
        private boolean mouseReleased = false;
        private int topX, topY;
        private float w, h;
        Ellipse2D ellipse = new Ellipse2D.Float(topX, topY, w, h);
        private BufferedImage buffer;
        private Graphics2D g2Buffer;
        private Color myLineColour;
        private int myLineWidth;
        private int toolChooser;
        private Shape shapeOld, shapeNew;
        private int xMouse, yMouse;
    
    
        public DrawPanel() {
            LineDetails lineDetails = new LineDetails();
            int toolChooser = lineDetails.toolChooser;
            int myLineWidth = lineDetails.myLineWidth;
            initComponents();
        }
    
    
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            setBackground(new java.awt.Color(200, 200, 255));
            addMouseListener(new java.awt.event.MouseAdapter() {
                public void mousePressed(java.awt.event.MouseEvent evt) {
                    formMousePressed(evt);
                }
                public void mouseReleased(java.awt.event.MouseEvent evt) {
                    formMouseReleased(evt);
                }
            });
            addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
                public void mouseDragged(java.awt.event.MouseEvent evt) {
                    formMouseDragged(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            );
        }// </editor-fold>                        
    
    
        private void formMousePressed(java.awt.event.MouseEvent evt) {                                  
    
            xStart = evt.getX();		// store start point
            yStart = evt.getY();
            xOld = xStart;
            yOld = yStart;
            drawing = true;
        }                                 
    
        private void formMouseReleased(java.awt.event.MouseEvent evt) {                                   
            xEnd = evt.getX();		// final point
            yEnd = evt.getY();
            mouseReleased = true;		// flag draw final line
            drawing = false;			// stop doing the draw
            paintComponent(getGraphics());	// force a redraw to see effect
        }                                  
    
        private void formMouseDragged(java.awt.event.MouseEvent evt) {                                  
            xEnd = evt.getX();		// follow mouse as dragged
            yEnd = evt.getY();
            paintComponent(getGraphics());	// force redraw to see effect
        }                                 
    
        // Variables declaration - do not modify                     
        // End of variables declaration                   
       
    
        public void paintComponent(Graphics gPanel) {
            if (buffer == null) {
                Dimension d = getSize();
                buffer = new BufferedImage(d.width, d.height,
                        BufferedImage.TYPE_INT_ARGB_PRE);
                myLineColour = new Color(0, 255, 0);
                myLineWidth = 8;
                toolChooser = 1;
                g2Buffer = (Graphics2D) buffer.getGraphics();
                g2Buffer.setColor(Color.white);
                g2Buffer.fillRect(0, 0, d.width, d.height);
                
            }
            if (drawing) {
                g2Buffer.setColor(Color.white);
                g2Buffer.setStroke(new BasicStroke(myLineWidth));
                g2Buffer.setXORMode(myLineColour);
                switch (toolChooser) {
                    case 1: //line
                        shapeOld = new Line2D.Float(xStart, yStart, xOld, yOld);
                        g2Buffer.draw(shapeOld);
                        shapeNew = new Line2D.Float(xStart, yStart, xEnd, yEnd);
                        g2Buffer.draw(shapeNew);
    
                        //I've removed the other cases to save space.
                    }
                xOld = xEnd;			 // store last end point
                yOld = yEnd;
                }
             if (mouseReleased) {
                g2Buffer.setColor(myLineColour);
                ellipse = new Ellipse2D.Float(xStart, yStart,
                        Math.abs(xEnd - xStart), Math.abs(yEnd - yStart));
                g2Buffer.draw(ellipse);
                mouseReleased = false;
            }
            gPanel.drawImage(buffer, 0, 0, this);
        }
    }
    
    
    
    
    
    
    
    
    
    
    public class LineDetails {
    
        public Color myLineColour;
        public int myLineWidth;
        public int toolChooser;
    
    
    
        public LineDetails() {
            DrawFrame drawFrame = new DrawFrame();
            Color myLineColour = drawFrame.myLineColour;
            int myLineWidth = drawFrame.myLineWidth;
            int toolChooser = drawFrame.toolChooser;
        }
    
    }
    Last edited by kaizen9001; 03-27-2011 at 08:43 PM.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    We can't compile your code, we can't run your code or test your code, so no, it's not an SSCCE, and I don't think that we can use it to help you.

  9. #9
    kaizen9001 is offline Member
    Join Date
    Mar 2011
    Posts
    13
    Rep Power
    0

    Default

    I can't compile my code either. That's the problem. I get a Stack Overflow Error because of the issue I described earlier.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Wait a minute, maybe we can get something useful from this. Please hang on...

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Your DrawFrame class contains this constructor:


    Java Code:
    public class DrawFrame extends javax.swing.JFrame {
       private DrawPanel drawPanel;
       //....
    
       public DrawFrame() {
          drawPanel = new DrawPanel();
          getContentPane().add(drawPanel, java.awt.BorderLayout.CENTER);
          initComponents();
    
       }


    Your DrawPanel contains this constructor:


    Java Code:
    public class DrawPanel extends javax.swing.JPanel {
       //....
    
       public DrawPanel() {
          LineDetails lineDetails = new LineDetails();
          int toolChooser = lineDetails.toolChooser;
          int myLineWidth = lineDetails.myLineWidth;
          initComponents();
       }


    And your LineDetails contains this constructor:


    Java Code:
    public class LineDetails {
       //....
    
       public LineDetails() {
          DrawFrame drawFrame = new DrawFrame();
          Color myLineColour = drawFrame.myLineColour;
          int myLineWidth = drawFrame.myLineWidth;
          int toolChooser = drawFrame.toolChooser;
       }


    So you've got infinite circular logic going on:
    DrawFrame creates a new DrawPanel object which creates a new LineDetails object which creates a new DrawFrame object which creates a new DrawPanel object which creates a new LineDetails object which creates a new DrawFrame object which ....

    So it makes sense that this code, which compiles, will never fully run since it will spend eternity creating these classes until Java runs out of memory and throws a StackOverflowError.

    The solution: don't do this. Instead if one class needs a reference to the other, pass it to the other via a constructor parameter or a setXXX setter method.

  12. #12
    kaizen9001 is offline Member
    Join Date
    Mar 2011
    Posts
    13
    Rep Power
    0

    Default

    Yeah I had worked out that this was going on from my error messages. I just had no idea how to get around it. I'll look up your suggestions.
    Thank's for the help!

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. infinite loop
    By javapink in forum New To Java
    Replies: 19
    Last Post: 03-06-2011, 02:28 AM
  2. how to end infinite loop
    By search4survival in forum New To Java
    Replies: 14
    Last Post: 10-25-2010, 08:59 AM
  3. Infinite loop
    By jDennis79 in forum New To Java
    Replies: 7
    Last Post: 08-13-2010, 11:45 PM
  4. Infinite Loop
    By bosoxfan in forum New To Java
    Replies: 3
    Last Post: 02-22-2010, 01:34 AM
  5. Infinite Loop
    By rclausing in forum New To Java
    Replies: 2
    Last Post: 01-23-2010, 10:11 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •