Previous Page

The Sieve of Eratosthenes- Java GUI

Copy and Paste the following code into your favorite Java Integrated Development Environment (IDE) - compile and run.

Here is the image file if you want.(NOTE: Not needed for the program to work.)
Place it in the same directory as your .java file eratosthenes_sieve.png


/***********************************************************************************
/ Name: Brian Butler
/ Professor: Gary Hartell
/ Date: April 10, 2011
/ Assignment:Sieve of Eratosthenes 
/								   
/					   					 Descripion:
/		This program uses the Sieve of Eratosthenes to find all of the prime numbers
/       up to and including the integer	entered by the user.       
/
************************************************************************************/

/***********************************************************************************
/										   	Algorithm:(taken from Wikipedia.com)
/
/		1. Create a list of consecutive integers from two to n: (2, 3, 4, ..., n)
/		2. Initially, let p equal 2, the first prime number
/		3. Stating from p, count up by p and cross out thus found numbers in the list
/			(which will be 2p,3p,4p, etc.)
/		4. find the first number not yet crossed out after p; let p now equal this 
/			number ( which is the next prime)
/		5. Repeat steps 3 and 4 until p is greater than n
/		6. All the numbers in the list whhich are not crossed out are prime    
/
************************************************************************************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import static java.lang.Math.*;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;



public class eratosthenesJFrame extends JFrame
{

	private JLabel  inputL;
					  
	private JTextField inputTF;
	
	private static JTextArea outputTA;
	
	private JScrollPane scrollText;//creates the scroll feature for JTextArea
														 
	private JButton calculateB, exitB, clearB;

	private CalculateButtonHandler cbHandler;
	private ExitButtonHandler ebHandler;
	private ClearButtonHandler clbHandler;	
	
	private static int WIDTH = 1024;
     private static int HEIGHT = 750;
		
   public eratosthenesJFrame()
    

	{
     Font font = new Font("Courier New", Font.BOLD, 20);
	Font font2 = new Font("Verdana Bold", Font.PLAIN, 32);
	Font font3 = new Font("Times New Roman", Font.BOLD, 20);
		
	JLabel inputL = new JLabel("Please enter an integer to find"+
						  " all the prime numbers up to that number:");
	inputL.setFont(font3);
						  
	inputTF = new JTextField(3);
	inputTF.setFont(font2);
	
	outputTA = new JTextArea("",10,10);
	outputTA.setFont(font);
	outputTA.setBorder(BorderFactory.createEmptyBorder(50, 50, 20, 40));
	outputTA.setLineWrap(true);
   outputTA.setWrapStyleWord(true);
	  
	   // the code below is for adding an image to the background of the window
       
	  	   final ImageIcon imageIcon = new ImageIcon("eratosthenes_sieve.png");
	      outputTA = new JTextArea("",10,10) {
         Image image = imageIcon.getImage();

      Image grayImage = GrayFilter.createDisabledImage(image);
      {
        setOpaque(false);
      }

      public void paint(Graphics g) {
        g.drawImage(grayImage, 0, 0, this);
        super.paint(g);
      }
    };
	outputTA.setFont(font);
	outputTA.setBorder(BorderFactory.createEmptyBorder(50, 50, 20, 40));
	outputTA.setLineWrap(true);
     outputTA.setWrapStyleWord(true);
		
    
     scrollText = new JScrollPane(outputTA);//adds the scroll feature to the outputTA
     scrollText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
 
		
	 calculateB = new JButton("Calculate");
      cbHandler = new CalculateButtonHandler();
      calculateB.addActionListener(cbHandler);
	 calculateB.setFont(font2);
	 
	 exitB = new JButton("EXIT");
      ebHandler = new ExitButtonHandler();
      exitB.addActionListener(ebHandler);
	 exitB.setFont(font2);
	 
	 clearB = new JButton("Clear All");
      clbHandler = new ClearButtonHandler();
      clearB.addActionListener(clbHandler);
	 clearB.setFont(font2);	 

	 
	 setTitle("Sieve of Erastosthenes");		
            
      Container myWindow = getContentPane();
      myWindow.setLayout(null);


	 
	       calculateB.setLocation(794, 5);
		  exitB.setLocation(525, 665);
		  clearB.setLocation(250, 665);
		  inputL.setLocation(6,5);
		  inputTF.setLocation(608,5);
		  scrollText.setLocation(5,50);		 
			
         
		  calculateB.setSize(210,40); 
            exitB.setSize(225, 40);
		  clearB.setSize(225, 40);
		  inputL.setSize(660,40);
		  inputTF.setSize(185,40);
		  scrollText.setSize(1000,610);
		  
		  myWindow.add(calculateB);          
            myWindow.add(exitB);
		  myWindow.add(clearB);
		  myWindow.add(inputL);
		  myWindow.add(inputTF);
		  myWindow.add(scrollText);
		 
		  
	 	  setSize(WIDTH, HEIGHT);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);       

 	  }
	  
 private class CalculateButtonHandler implements ActionListener
 {
     public  void actionPerformed(ActionEvent e)
     { 	
	      String arraySizeStr;
 	      int arraySize;		
	
			arraySize = Integer.parseInt(inputTF.getText());
			int y = (int) sqrt(arraySize);

      boolean[] notPrime = new boolean[arraySize + 1];// Must add 1 to the 
											// array since the array starts out
											// at 0, otherwise the arraySize is not
											// big enough and will give an 
											// ArrayIndexOutOfBoundsException         

      for (int num = 2; num <= y; num++)// will run through the entire
													 // for loop as long as num is 
													 // less than or equal to the 
													 // user supplied arraySize.
													 // Must start with 2 for it
													 // to work, though.         
		{
            if (!notPrime[num])  //if the array's expression (num) is
											//NOT not prime then it will prlong out
											//the prime number. So these numbers 
											//will be prime and then numbers that
											//are divisible by this number will
											//be put in the notPrime array       
											//Without this if statement, the 
											//program will prlong every number
											//in the array starting with 2            
	      	{
                  outputTA.append(num + " ");// Printss each Prime Number  
															// one at a time. The number
															//	 two prints right away.  
						
                  for (int k = num*num ; k <= arraySize; k += num)
						   //sets k equal to 2 times 2 initially.
						   //So k = 4 and 4 will be discarded longo the notPrime 
							//array. k then updates to k + num (which is 4 + 2).
						   //So now 6 is discarded..and so on.Until k is greater
						   //than the users input for the arraySize.
							//This FOR LOOP gets rid of all of the multiples of
							//the next prime number                   		   	
					 
				
                	 notPrime[k] = true;//numbers not primes go here
			   }
		 }
					
					 for (int n = y; n <= arraySize;n++)
					 if (!notPrime[n]) 
                  outputTA.append(n + " ");					  
     }
			
					
									
}   
		
   	 private class ExitButtonHandler implements ActionListener
       {
       public void actionPerformed(ActionEvent e)
       {
           System.exit(0);//allows the exit button to close the JFrame window       
       }
    }// End of EXIT BUTTON actionPerformed   
	 
	 	 private class ClearButtonHandler implements ActionListener
    {
       public void actionPerformed(ActionEvent e)
       {
                 inputTF.setText("");
			  outputTA.setText("");
			  inputTF.requestFocusInWindow();
       }
    }


   public static void main(String[] args)
   {	 
       eratosthenesJFrame sieveObject = new eratosthenesJFrame();
	   sieveObject.setLocationRelativeTo(null);
   }	
}
	
//END OF CODE