Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 215
  • Last Modified:

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


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?
0
Painfree888
Asked:
Painfree888
3 Solutions
 
DeanHorakCommented:
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
0
 
Manikandan ThiagarajanSenior consultantCommented:
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)

{

}
0
 
Manikandan ThiagarajanSenior consultantCommented:
what is your exact problem now
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> 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 :)
0
 
Painfree888Author 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.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now