Hi All

Here is a Simple Java Application based on Swings and Event Handling which calculates the Factorial of a Number in a given text box and display it in another text box on clicking the Calculate Factorial Button.

No validations have been performed.

Level-Beginner

Program – CalFactorial.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CalFactorial extends JFrame implements ActionListener  {
 JLabel l1,l2;
 JButton b1;
 JTextField tf1, tf2;
 CalFactorial()  {
 l1 = new JLabel("Number : ");
 l2 = new JLabel("Factorial : ");
 tf1 = new JTextField(10);
 tf2 = new JTextField(10);
 b1 = new JButton("Calculate Factorial");
 setLayout(new FlowLayout());
 add(l1); add(tf1);
 add(l2); add(tf2);
 add(b1);
 b1.addActionListener(this);
 }
public void actionPerformed(ActionEvent ae)  {
 String s = ae.getActionCommand();
 if(s.equals("Calculate Factorial"))  {
 String str = tf1.getText();//getting the number from Number TextField
 int num= Integer.parseInt(str);
 int fact = 1;
 //Calculating the Factorial
 for(int i=num; i>=1; i- -){
 fact = fact * i;
 }
 tf2.setText(""+fact);
 }
}
 public static void main(String[] args)  {
 CalFactorial cr = new CalFactorial();
 cr.setTitle("Swings Sample Program-CalFactorial");
 cr.setSize(400,300);
 cr.setVisible(true);
 cr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}

Save this program as CalFactorial.java

To Compile type at the prompt

>javac CalFactorial.java

To run the program type

>java CalFactorial

Snapshots

Here it look like this

Here Factorial of 7 is displayed.

Advertisements