We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

Simple program, or so I thought. Can anyone tell me why this does not work?

Painfree888
Painfree888 asked
on
Medium Priority
230 Views
Last Modified: 2008-02-01

Attempting to learn Java, and found an exercise in a book that I am attempting to make work. The program paints random triangles on a the screen, with the maximum size of the triangle and number of triangles determined by the user. The user is prompted for these values after they hit the Start button.

The problem I am having is this: when the Start button is clicked, the user is prompted for the aforementioned values. Then, nothing happens. I've been playing around with this, and you will notice that I setup the Start button and add it to the container in the constructor. But, I handle making the Start button an action listener using an anonymous inner class in method Paint. I am doing this because as soon as I setVisible ( true ), the paint method fires, meaning that whatever I have in there attempts to run before the Start button is pressed by the user (I had attempted to setup the Start button as an event handler in the constructor, but figured if I did it in method paint, I could control when the code in the method runs).

Something tells me my approach is completely hosed, but I can't figure out how to get this to work, thus my question here.

Here is the code:

package mypackage1;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.*;
import javax.swing.*;

public class RandomTriangles extends JFrame {
   int maxTriCount, maxTriSize;
   Container container;
   JButton start;
   Graphics2D g2d;
   GeneralPath tShape;
   
   public RandomTriangles()
   {
      super( "Arek Grantham: Random Triangle Generator" );
     
      start = new JButton("Start");
     
      container = getContentPane();
      container.setLayout( new FlowLayout() );
      container.add( start );
     
      getContentPane().setBackground( Color.WHITE );
      setSize( 500,500 );
      setVisible( true );
   }

 
   public void paint( Graphics g )
   {    
      super.paint( g );
     
      g2d = ( Graphics2D ) g;
      tShape = new GeneralPath();
     
      start.addActionListener(
        new ActionListener()
        {
          public void actionPerformed( ActionEvent event )
          {    
            int i,h,k;
            int r,gr,b;
            int x[] = new int[3];
            int y[] = new int[3];
           
            maxTriCount = Integer.parseInt(JOptionPane.showInputDialog("Enter Number of Triangles to draw:"));
            maxTriSize = Integer.parseInt(JOptionPane.showInputDialog("Enter Maximum Size of Triangles to draw:"));
         
            for ( h = 0; h < maxTriCount; h++ )
            {
              r = (int)(Math.random()*256);
              gr = (int)(Math.random()*256);
              b = (int)(Math.random()*256);
             
              for (i=0; i<3; i++)
              {
                 x[i] = 1 + ( int ) (Math.random() * maxTriSize );
                 y[i] = 1 + ( int ) (Math.random() * maxTriSize );
              }  
       
              tShape.moveTo( x[ 0 ], y[ 0 ] );
             
              for ( int count = 1; count < x.length; count++ )
                 tShape.lineTo( x[ count ], y[ count ] );
       
              tShape.closePath();  // close the shape
       
              // set random drawing color
              g2d.rotate( Math.PI/(int)(Math.random()*256) );
              g2d.setColor( new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256)));
              g2d.fill( tShape );  // draw filled triangle
              repaint();
            }//end for
         
          }//end actionPerfomed
        }//end ActionListener      
      );//end addActionListener
   } // end method paint
 
   // execute application
   public static void main( String args[] )
   {
      RandomTriangles randomTriangles = new RandomTriangles();
      randomTriangles.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }
 
} // end class


*****

Any ideas?
Comment
Watch Question

I moved the actionlistener code back out to the constructor, initialized tShape to null and added the call to Graphics2d.draw method in the paint method (after testing for tShape of null).
-----------------------------------
package mypackage1;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.*;
import javax.swing.*;

public class RandomTriangles extends JFrame {
   int maxTriCount, maxTriSize;
   Container container;
   JButton start;
   Graphics2D g2d;
   GeneralPath tShape = null;
   
   public RandomTriangles()
   {
      super( "Arek Grantham: Random Triangle Generator" );
     
      start = new JButton("Start");
      start.addActionListener(
                  new ActionListener()
                  {
                    public void actionPerformed( ActionEvent event )
                    {    
                      int i,h,k;
                      int r,gr,b;
                      int x[] = new int[3];
                      int y[] = new int[3];

                      tShape = new GeneralPath();
                      maxTriCount = Integer.parseInt(JOptionPane.showInputDialog("Enter Number of Triangles to draw:"));
                      maxTriSize = Integer.parseInt(JOptionPane.showInputDialog("Enter Maximum Size of Triangles to draw:"));
                  
                      for ( h = 0; h < maxTriCount; h++ )
                      {
                        r = (int)(Math.random()*256);
                        gr = (int)(Math.random()*256);
                        b = (int)(Math.random()*256);
                      
                        for (i=0; i<3; i++)
                        {
                           x[i] = 1 + ( int ) (Math.random() * maxTriSize );
                           y[i] = 1 + ( int ) (Math.random() * maxTriSize );
                        }  
                
                        tShape.moveTo( x[ 0 ], y[ 0 ] );
                      
                        for ( int count = 1; count < x.length; count++ )
                           tShape.lineTo( x[ count ], y[ count ] );
                
                        tShape.closePath();  // close the shape
                
                        // set random drawing color
                        g2d.rotate( Math.PI/(int)(Math.random()*256) );
                        g2d.setColor( new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256)));
                        g2d.fill( tShape );  // draw filled triangle
                        repaint();
                      }//end for
                  
                    }//end actionPerfomed
                  }//end ActionListener      
                );//end addActionListener
     
      container = getContentPane();
      container.setLayout( new FlowLayout() );
      container.add( start );
     
      getContentPane().setBackground( Color.WHITE );
      setSize( 500,500 );
      setVisible( true );
   }

 
   public void paint( Graphics g )
   {    
      super.paint( g );
     
      g2d = ( Graphics2D ) g;
     
      if(tShape!=null)
            g2d.draw(tShape);
     
    } // end method paint
 
   // execute application
   public static void main( String args[] )
   {
      RandomTriangles randomTriangles = new RandomTriangles();
      randomTriangles.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
   }
 
} // end class

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Manikandan ThiagarajanSenior consultant
Commented:
public void paint( Graphics g )
   {    
      super.paint( g );
     
      g2d = ( Graphics2D ) g;
     
      if(tShape!=null)
           g2d.draw(tShape);
     
    } // end method paint

replace public void paint( Graphics g ) to

public void paintComponent(Graphics g)

{

}
Manikandan ThiagarajanSenior consultant

Commented:
what is your exact problem now
Mayank SPrincipal Technologist
CERTIFIED EXPERT
Commented:
>> I moved the actionlistener code back out to the constructor

Correct, it should not be in the paint () method otherwise it will be added everytime paint () is called :)

Author

Commented:


Well, I actually got it to work before coming back here, but as I read through what you guys have done, I see your input is better than my solution. I had thought about moving the code in the paint method to the action listener, which is why I tried to move the aic down to the paint method. Right idea but wrong way around.

Thanks for the help guys. Going to increase points and split them out.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.