lunedì 16 marzo 2009

CALCOLATRICE (ESERCITAZIONE)

/*esercitazione calcolatrice*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class CalcolatriceCompito{

JFrame f=new JFrame("Calcolatrice");
JLabel l1=new JLabel("1° operando :");
JLabel l2=new JLabel("2° operando :");
JLabel l3=new JLabel("risultato : ");
JTextField f1=new JTextField();
JTextField f2=new JTextField();

JButton b1=new JButton("+");
JButton b2=new JButton("-");
JButton b3=new JButton("X");
JButton b4=new JButton("/");
JButton b5=new JButton("clear");
JButton b6=new JButton("=");
JLabel risultato=new JLabel();
JPanel p1=new JPanel();
JPanel p2=new JPanel();
char valori;

public CalcolatriceCompito(){

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400,400);
p1.setLayout(new GridLayout(3,2));
p2.setLayout(new GridLayout(2,3));
p1.add(l1);
p1.add(f1);
p1.add(l2);
p1.add(f2);
p1.add(l3);
p1.add(risultato);
p2.add(b1);
p2.add(b2);
p2.add(b3);
p2.add(b4);
p2.add(b5);
p2.add(b6);
f.add (BorderLayout.NORTH,p1);
f.add (BorderLayout.CENTER,p2);

b1.addActionListener(new Addizione());
b2.addActionListener(new Sottrazione());
b3.addActionListener(new Moltiplicazione());
b4.addActionListener(new Divisione());
b5.addActionListener(new Clear());
b6.addActionListener(new Uguale());

f.setVisible(true);
}

public class Addizione implements ActionListener{
public void actionPerformed(ActionEvent event){
valori='+';
}
}


public class Sottrazione implements ActionListener{
public void actionPerformed(ActionEvent e){
valori='-';
}
}

public class Moltiplicazione implements ActionListener{
public void actionPerformed(ActionEvent e){
valori='X';
}
}

public class Divisione implements ActionListener{
public void actionPerformed(ActionEvent e){
valori='/';
}
}

public class Uguale implements ActionListener{
public void actionPerformed(ActionEvent event){
String testo1=f1.getText();
String testo2=f2.getText();
int t=Integer.parseInt(testo1);
int t1=Integer.parseInt(testo2);
double r=0;
if(valori=='+') r=t+t1;
if(valori=='-') r=t-t1;
if(valori=='X') r=t*t1;
if(valori=='/') r=t/t1;
String rr=Double.toString(r);
risultato.setText(rr);

}
}

public class Clear implements ActionListener{
public void actionPerformed(ActionEvent e){
f1.setText("");
f2.setText("");
risultato.setText("");
}
}


public static void main (String []args){
CalcolatriceCompito f=new CalcolatriceCompito();
}

}
____________________________________________________________________________________
Free Image Hosting at www.ImageShack.us

QuickPost Quickpost this image to Myspace, Digg, Facebook, and others!

Nessun commento: