Hi All

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

No validations have been performed.

Level-Beginner

Program – CalCube.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class CalCube extends JFrame implements ActionListener {
JLabel l1,l2;
JButton b1;
JTextField tf1, tf2;
CalCube() {
l1 = new JLabel("Number : ");
l2 = new JLabel("Cube : ");
tf1 = new JTextField(10);
tf2 = new JTextField(10);
b1 = new JButton("Calculate Cube");
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 Cube"))  {
String str = tf1.getText();
int num= Integer.parseInt(str);
tf2.setText(""+num*num*num);
}
}


public static void main(String[ ] args) {
CalCube cr = new CalCube();
cr.setTitle("Swings Sample Program-CalulateCube");
cr.setSize(400,300);
cr.setVisible(true);
cr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Save this program as CalCube.java

To Compile type at the prompt

>javac CalCube.java

To run the program type

>java CalCube

Snapshots

Here it look like this


Enter the Number whose cube you want to calculate in the Number Text Field and then Click on the Calculate Cube Button.


Here Cube of 2 has been calculated and displayed.

Advertisements