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.

Criminal lawyer attorney lawyer mesothelioma Psychic for free DONATE A CAR IN MARYLAND Make money online Australia cash out structured settlement Mobile casino CAR INSURANCE IN SOUTH DAKOTA Car Insurance Companies firm law mesothelioma DONATE YOUR CAR SACRAMENTO WordPress hosting Online casino Casino selling my structured settlement Structures Annuity Settlement Social media management truck accident attorney texas DUI lawyer Social media tools structured settlement buyer Donate car for tax credit Live casino Mesothelioma Law Firm Home Phone Internet Bundle Seo company Claim orlando criminal attorney online criminal justice degree Php programmers for hire illinois mesothelioma lawyer car accident lawyers west palm beach refinance with bad credit structured settlement brokers Motor Replacements Hire php developers Online Criminal Justice Degree Casino reviews los angeles workers compensation lawyers donate your car for kids Dedicated Hosting Dedicated Server Hosting New social media platforms mesothelioma survival rates Cheap Car Insurance for Ladies ANNUITY SETTLEMENT Best Criminal Lawyers in Arizona alabama mesothelioma lawyer DONATE CAR FOR TAX CREDIT Online Christmas cards ASBESTOS LAWYERS NEUSON CAR INSURANCE QUOTES MN business voip solutions home phone internet bundle Computer science classes online Hire php programmers Dwi lawyer VIRTUAL DATA ROOMS Criminal defense lawyer Donate Cars in MA DONATE CARS IN MA asbestos lung cancer Dallas Mesothelioma Attorneys Criminal defense attorneys Florida Business finance group Email Bulk Service accident attorney in los angeles personal accident attorney primary pulmonary hypertension car donate integrated ehr refinance with poor credit MET AUTO Criminal lawyer Miami washington mesothelioma attorney Service business software personal injury lawyer personal injury solicitor Best Seo company Donating Used Cars to Charity WordPress themes for designers Custom Christmas cards supportpeachtreecom Massage School Dallas Texas Paperport Promotional Code Italian cooking school forensics online course Cheap Auto Insurance in VA cash annuity illinois law lemon mesothelioma settlement amounts car insurance in south dakota Hire php developer houston tx auto insurance most profitable internet business Bankruptcy lawyer Php programmers windows phone for business mesothelioma settlements amounts asbestos mesothelioma lawsuit Royalty free images stock Best social media platforms WEBEX COSTS Social media platforms Auto Mobile Insurance Quote truck accident attorney los angeles selling structured settlement georgia truck accident lawyer Seo companies Best social media platforms for business Donating a car in Maryland structured settlement sell mesothelioma lawsuits mesothelioma attorneys california Car Insurance Quotes Colorado virtual data rooms Social media platforms for business Custom WordPress theme designer Royalty Free Images Stock Seo services Business management software PSYCHIC FOR FREE best accident attorneys Mortgage Adviser pharmacist jobs in chicago Forensics Online Course Tech school Met auto utah mesothelioma lawyer los angeles auto accident attorneys Photo Christmas cards How to Donate A Car in California better conferencing calls Motor replacements Psd to WordPress Social media examiner Automobile Accident Attorney Insurance Car insurance quotes Colorado Html email best consolidation loan student Christmas cards mesothelioma lawyer virginia lawsuit mesothelioma holland michigan college Donate Old Cars to Charity Proud Italian cook Psd to html Car Donate accident attorney orange county Online Stock Trading boca raton personal injury attorney structured settlement blog Adobe illustrator classes BEST CRIMINAL LAWYER IN ARIZONA WordPress theme designers Social media strategies Virtual Data Rooms Learning adobe illustrator Car Accident Lawyers mesothelioma attorney florida structured settlemen Social media campaigns Donate Car to Charity California Donate Car for Tax Credit mesothelioma Donate Your Car for Kids fortis health insurance temporary Donate Your Car Sacramento criminal defense federal lawyer Sell Annuity Payment michigan motorcycle accident lawyer Asbestos Lawyers donate old cars to charity dui lawyer scottsdale Annuity Settlements Nunavut Culture Dayton Freight Lines chicago hair laser removal Car Insurance Quotes Utah Hard drive Data Recovery Services Donate a Car in Maryland Cheap Domain Registration Hosting Injury Lawyers Donating a Car in Maryland dallas mesothelioma attorneys accident lawyers in los angeles Donate Cars Illinois Criminal Defense Attorneys Florida how to donate a car in california Car Insurance Quotes HOLLAND MICHIGAN COLLEGE Life Insurance Co Lincoln car accident lawyer michigan california motorcycle accident lawyer Holland Michigan College online colledges Online Motor Insurance Quotes Online Colleges Asbestos Lung Cancer Online Classes anti spam exchange server World Trade Center Footage SELL ANNUITY PAYMENT Psychic for Free life insurance co lincoln Low Credit Line Credit Cards Car Insurance Quotes MN Donate your Car for Money mesothelioma cases Motor Insurance Quotes Met Auto personal injury attorney springfield mo Neuson adverse credit remortgage mesothelioma attorney assistance CAR INSURANCE QUOTES COLORADO new mexico mesothelioma lawyer mesothelioma attorney illinois att call conference CAR INSURANCE QUOTES PA PHD on Counseling Education CAR INSURANCE QUOTES UTAH Car Insurance Quotes PA Car Insurance in South Dakota DAYTON FREIGHT LINES Webex Costs personal injury accident lawyer Cheap Car Insurance in Virginia Register Free Domains Better Conference Calls Register free domains Futuristic Architecture mesotheolima HOME PHONE INTERNET BUNDLE cheap car insurance in virginia mesothelioma settlements REGISTER FREE DOMAINS Online College Course benchmark lending CHEAP DOMAIN REGISTRATION HOSTING Auto Accident Attorney PAPERPORT PROMOTIONAL CODE Data Recovery Raid Car insurance quotes MN personal injury lawyer sarasota fl PhD in counseling education Personal Injury Lawyers Online motor insurance quotes business administration masters

No hay comentarios:

Publicar un comentario