sábado, 7 de diciembre de 2013

Mini Calculadora en Java [Swing Biblioteca Gráfica] – cancer – Credit – Miami

En Java existe una biblioteca gráfica (Componentes Swing) la cual incluye widgets para la interfaz gráfica de usuario (cajas de texto, botones, menús entre muchos otros...).

Haciendo uso de ésta biblioteca vamos a crear una "MiniCalculadora" con las operaciones básicas como lo son: suma, resta, multiplicación y división.

Para ésta "MiniCalculadora" haremos uso de 3JTextField (campos de texto) dos para los operando y uno para mostrar el resultado , 5JButtons (botones) 4 para las operaciones 1 para salir de la aplicación y 1 para mostrar el about, a su vez 4JLabels para mostrar ciertos textos en la ventana.

Operar.java //Calculadora
  1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import javax.swing.*;

import java.awt.event.*; // agregamos esto tambien para el boton.

public class Operar extends JFrame implements ActionListener {
private JTextField operando1, operando2, resultado;
private JButton restar, sumar, multiplicar, dividir, cerrar, acerca;
private JLabel titulo, texto1, texto2, result;
public Operar(){
setLayout(null);
//text fields
operando1 = new JTextField();
operando1.setBounds(100, 100, 100, 20);
add(operando1);
operando2 = new JTextField();
operando2.setBounds(100, 130, 100, 20);
add(operando2);
resultado = new JTextField();
resultado.setBounds(100, 160, 100, 20);
add(resultado);
//buttons
restar = new JButton("Restar");
restar.setBounds(220, 100, 100, 50);
add(restar);
restar.addActionListener(this);

sumar = new JButton("Sumar");
sumar.setBounds(220, 160, 100, 50);
add(sumar);
sumar.addActionListener(this);

multiplicar = new JButton("Multiplicar");
multiplicar.setBounds(220, 220, 100, 50);
add(multiplicar);
multiplicar.addActionListener(this);

dividir = new JButton("Dividir");
dividir.setBounds(220, 280, 100, 50);
add(dividir);
dividir.addActionListener(this);

cerrar = new JButton("Salir");
cerrar.setBounds(100, 200, 100, 50);
add(cerrar);
cerrar.addActionListener(this);

acerca = new JButton("About");
acerca.setBounds(100, 260, 100, 50);
add(acerca);
acerca.addActionListener(this);
//labels
titulo = new JLabel("Calculadora francves v1.0");
titulo.setBounds(130, 40, 200, 30);
add(titulo);

texto1 = new JLabel("Primer Valor: ");
texto1.setBounds(10, 95, 200, 30);
add(texto1);

texto2 = new JLabel("Segundo Valor: ");
texto2.setBounds(10, 125, 200, 30);
add(texto2);

result = new JLabel("Resultado: ");
result.setBounds(10, 155, 200, 30);
add(result);
}



public void actionPerformed(ActionEvent e) {
if(e.getSource() == restar){
String oper1=operando1.getText();
String oper2=operando2.getText();
int num1=Integer.parseInt(oper1);
int num2=Integer.parseInt(oper2);
int resul=num1-num2;
String total=String.valueOf(resul);
resultado.setText(total);
}
if(e.getSource() == sumar){
String oper1=operando1.getText();
String oper2=operando2.getText();
int num1=Integer.parseInt(oper1);
int num2=Integer.parseInt(oper2);
int resul=num1+num2;
String total=String.valueOf(resul);
resultado.setText(total);
}
if(e.getSource() == multiplicar){
String oper1=operando1.getText();
String oper2=operando2.getText();
int num1=Integer.parseInt(oper1);
int num2=Integer.parseInt(oper2);
int resul=num1*num2;
String total=String.valueOf(resul);
resultado.setText(total);
}
if(e.getSource() == dividir){
String oper1=operando1.getText();
String oper2=operando2.getText();
int num1=Integer.parseInt(oper1);
int num2=Integer.parseInt(oper2);
int resul=num1/num2;
String total=String.valueOf(resul);
resultado.setText(total);
}

if(e.getSource() == cerrar){
System.exit(0);
}

if(e.getSource() == acerca){
JOptionPane.showMessageDialog(null, "Calculadora francves v1.0 \n Sigueme en twitter @francves");
}
}

public static void main(String[] ar){
Operar ope = new Operar();
ope.setBounds(10, 10, 400, 400);
ope.setResizable(false);
ope.setVisible(true);
}
}

Explicación:


importjavax.swing.*;


importjava.awt.event.*;


Debemos importar esos paquetes para poder manejar las componentes Swing que vamos a utilizar en la calculadora.

Declaramos cada componente y luego le empezamos a dar ciertas características como lo son el tamaño y la posición en la pantalla.

restar.setBounds(220, 100, 100, 50);

La linea anterior le está dando ciertas características al botón "restar.setBounds(x, y, width, height);" con el parámetro "X" indicamos que tan a la izquierda o derecha se encuentra el boton, con el parámetro "Y" indicamos que tan arriba o abajo está el botón. En el tercer parámetro "width" como allí lo indica en lo ancho del botón y "Height" lo alto del botón.

Luego, debemos definir la acción que ejecutará cada botón al hacer clic sobre el. Seguimos con el ejemplo del botón "restar".


if(e.getSource()== restar){


Stringoper1=operando1.getText();


String oper2=operando2.getText();


int num1=Integer.parseInt(oper1);


int num2=Integer.parseInt(oper2);


int resul=num1-num2;


String total=String.valueOf(resul);


resultado.setText(total);


}


Con el método .getText() obtenemos el valor ingresado dentro de los campos de texto. Luego, estos valores ingresan como un tipo de datoSTRING por ello hay que convertirlos a un tipo de dato con el cual podamos realizar operaciones matemáticas, en este caso lo convertimos a int(entero). Esa conversión de tipo de dato la realizamos con el métodoInteger.parseInt() pasándole como parámetro la variable que ha guardado el valor ingresado, en nuestro caso sería la variable oper1.
Después de realizar esa conversión, el dato lo debemos guardar en una nueva variable de tipo entero.
Realizamos las operaciones respectivas y al tener un resultado, ese valor lo debemos convertir en un dato STRINGpara luego mostrarlo en el campo de texto correspondiente al resultado. Esto lo hacemos con el métodoString.valueOf(resul)pasándole como parámetro la variable que almacena el resultado. Por último Asignamos el valor de la nueva variable de tipo string que contiene el resultado al campo de texto que lo mostrará en pantalla.


1 ope.setBounds(10,10,400,400);


2 ope.setResizable(false);


3 ope.setVisible(true);


Si desean cambiar el tamaño de la ventana modifiquen el valor 400 al que ustedes deseen. Recordar que el métodosetBounds(10, 10, 400, 400);definen la posición en pantalla (en éste caso de la ventana) y el tamaño de la misma. Si desean modificar el tamaño de la pantalla a su gusto en el momento que están ejecutando el programa camabien el parámetro del metodoope.setResizable(false); de false a true.
Por último el método setVisible(true); si cambiamos el parámetro de true a false haremos invisible la ventana.

ScreenShot del programa:


Consideraciones:
La calculadora realiza operaciones con datos enteros, si desean hacerlo con datos reales (float) deben hacer uso del métodoFloat.parseFloat(Variable que deseo convertir su valor en numero real); y luego de realizar las operaciones convierte el resultado a String de la misma manera como lo hicimos previamente.

Motor Replacements Make money online Australia Asbestos Lung Cancer Massage School Dallas Texas MESOTHELIOMA LAW FIRM federal criminal defense attorney benchmark lending CRIMINAL DEFENSE ATTORNEYS FLORIDA Casino Sell Annuity Payment Donate Cars in MA Online casino Business Voip Solutions asbestos lung cancer personal injury law firm Online Stock Trading Html email Annuity Settlements hair removal washington dc Car Insurance Quotes MN Casino reviews DALLAS MESOTHELIOMA ATTORNEYS CAR DONATE email bulk service Donate your car for money Life insurance co Lincoln HARDDRIVE DATA RECOVERY SERVICES Mobile casino car insurance quotes colorado ASBESTOS LAWYERS Futuristic Architecture LIFE INSURANCE CO LINCOLN Criminal lawyer cheap car insurance in virginia Mesothelioma Law Firm Dwi lawyer Insurance Donate a Car in Maryland Adobe illustrator classes Bankruptcy lawyer california law lemon Donate Your Car for Kids structure settlements Tech school motorcycle accident lawyer california mesothelioma attorney illinois DONATE OLD CARS TO CHARITY Data Recovery Raid Custom WordPress theme designer Register Free Domains Learning adobe illustrator canada personals yahoo Live casino Hire php developers donate old cars to charity st louis mesothelioma attorney yahoo web hosting california mesothelioma attorney compare life assurance Cheap Auto Insurance in VA DUI lawyer Email Bulk Service georgia truck accident lawyer ONLINE COLLEDGES structured settlement annuity companies houston mesothelioma attorney Cheap car insurance in Virginia Business finance group Home Phone Internet Bundle mortgage adviser DONATE CARS IN MA dallas mesothelioma attorneys refinance with bad credit Seo company MET AUTO Hire php developer Christmas cards paperport promotional code Hire php programmers Paperport Promotional Code asbestos lawyers ROYALTY FREE IMAGES STOCK buy structured settlements personal injury attorney torrance Personal Injury Law Firm CHEAP AUTO INSURANCE IN VA Automobile Accident Attorney Psd to html Social media platforms for business Service business software Best social media platforms for business personal injury attorney springfield mo Criminal defense lawyer selling annuity REGISTER FREE DOMAINS Neuson MASSAGE SCHOOL DALLAS TEXAS Cheap Domain Registration Hosting mesothelioma attorney florida google affiliate Php programmers for hire Custom Christmas cards Best Criminal Lawyers in Arizona Computer science classes online PHD IN COUNSELING EDUCATION mesothelioma litigation Php programmers Seo companies Car Donate mesotheolima New social media platforms Social media campaigns STRUCTURED ANNUITY SETTLEMENT Car insurance quotes Utah bowne virtual data room structured settlemen Insurance Companies Motor Insurance Quotes Seo services DONATE YOUR CAR SACRAMENTO WordPress theme designers online motor insurance quotes illinois law lemon Online Motor Insurance Quotes integrated ehr Best Seo company cash out structured settlement Business management software CAR INSURANCE QUOTES UTAH Car insurance quotes pa mesothelioma symptoms Car Insurance Quotes Colorado Proud Italian cook Best social media platforms Online Christmas cards structured settlement brokers Dayton Freight Lines Social media tools best accident attorneys Psd to WordPress Royalty Free Images Stock Car insurance quotes MN Photo Christmas cards WordPress themes for designers mesothelioma attorney DONATING USED CARS TO CHARITY Social media management PAPERPORT PROMOTIONAL CODE WordPress hosting DONATE YOUR CAR FOR KIDS Social media examiner Psychic for Free Psychic for free Paperport promotional code Cheap Car Insurance in Virginia DONATE A CAR IN MARYLAND Social media platforms diagnosed with mesothelioma sell annuity payment Life Insurance Co Lincoln Donate your car for kids Italian cooking school Forensics Online Course Auto Mobile Shipping Quote Low Credit Line Credit Cards mesothelioma survival rates structured settlements annuities Social media strategies royalty free images stock home phone internet bundle Hard drive Data Recovery Services Auto Mobile Insurance Quote Donate Car to Charity California auto insurance cost by state Donate Car for Tax Credit Donate Your Car Sacramento World Trade Center Footage World trade center footage new york mesothelioma law firm miami personal injury attorney ONLINE MOTOR INSURANCE QUOTES How to Donate A Car in California Dayton freight lines new mexico mesothelioma lawyer uk homeowner loans Asbestos Lawyers Structures Annuity Settlement buyers of structured settlements Car insurance quotes Colorado CAR ACCIDENT LAWYERS auto accident attorney structured settlement cash out Nunavut Culture PHD on Counseling Education car insurance quotes WebEx costs mesothelioma claims structured settlement company mesothelioma law firm Donating a Car in Maryland Donate Cars Illinois structured settlement buyers Criminal Defense Attorneys Florida accident car florida lawyer Car Insurance Quotes Utah mesothelioma lawsuit FUTURISTIC ARCHITECTURE Holland Michigan College NUNAVUT CULTURE mesothelioma lawyers san diego Online Colleges Online Classes car accident lawyers los angeles CAR INSURANCE IN SOUTH DAKOTA supportpeachtreecom Donate Old Cars to Charity better conferencing calls Dallas Mesothelioma Attorneys Donate your Car for Money Met Auto mesothelioma cases CHEAP DOMAIN REGISTRATION HOSTING Donating Used Cars to Charity Car Insurance Quotes PA Car Insurance Companies Claim lawyers accidents Car Insurance in South Dakota Webex Costs Cheap Car Insurance for Ladies criminal defense attorneys florida fortis health insurance temporary Better Conference Calls virtual data rooms Mortgage Adviser most profitable internet business Futuristic architecture structured settlement need cash now seattle mesothelioma lawyer car accident lawyer in san diego Virtual Data Rooms Online College Course small business administration sba Auto Accident Attorney Car Accident Lawyers online criminal justice degree los angeles auto accident attorneys Criminal lawyer Miami mesothelioma lawyer california WEBEX COSTS

No hay comentarios:

Publicar un comentario