Conversor de unidades con interfaz gráfica 2.0 [ESP-ENG] | Java

¿Qué tal? Estoy por acá de nuevo con más Java, esta vez con una actualización al conversor de unidades que he estado haciendo a modo de práctica. Esta actualización incluye varias mejoras interesantes, aunque no le di prioridad a las mejoras visuales, para la próxima actualización espero hacerlo. Si quieres echar un ojo a la versión anterior clica aquí.

What's up? I'm here again with more Java, this time with an update to the unit converter that I've been doing as a practice. This update includes several interesting improvements, although I didn't give priority to the visual improvements, for the next update I hope to do it. If you want to take a look at the previous version click here.


Portada post programacion, tech.gif

JAVA SEPARATOR PSD FILE.png

Para empezar añadí una función para redondear los doubles de manera que no salgan tantos decimales en pantalla y la lectura sea más sencilla para el usuario. La función se llama "formatearDecimales" y pide dos parámetros que son el número a "formatear" y el número de decimales deseados. Para este conversor fijé el número en 3 decimales.

Esta función no es propia, sino que la encontré en un blog que explicaba varios métodos para redondear en java, la fuente está al final de esta publicación.

La siguiente mejora es en materia de reducir la redundancia, pues dado que repetía mucho las líneas de:

numberConverted = formatearDecimales(numberConverted, 3);
fieldTwo.setText(String.valueOf(numberConverted));

Entonces decidí hacer una función que al final aplica el formateo del double y la asignación de valor al campo que refleja la conversión en pantalla. Sin embargo me encontré con el problema de que esto solo se debía aplicar si una de las condiciones se cumplía, por ello busqué como se aplicaba un "finally" al estilo Python en Java e implementé el código en la función correspondiente a cada conversión.

Este "finally" se basa en apoyarse en un boolean "doFinally" que será falso solo si no se cumple ninguna de las condiciones de conversión, para luego ser filtrado en un if que permitirá que se ejecute el formateo y asignación de texto en el campo solo si "doFinally" es verdadero (si se cumplió alguna de las condiciones). Este método lo hallé en StackOverFlow, la fuente está al final de esta publicación.

También añadí una validación para el caracter "-", pues es necesario tomarlo en cuenta en las temperaturas. Esta validación está en la función numberValidator. Para evitar redundancias en la conversión de temperatura y masa, hice una función llamada "fieldValidatorBasic" que incluye los casos que se repiten en los tres tipos de unidades.

La mejora más evidente, aunque ya la he mencionado indirectamente, es que se añadieron los tipos de unidades: temperatura y masa. Las fórmulas están expresadas en las funciones "temp_unitConverter" y "weight_unitConverter", todo con el pseudo-finally antes mencionado para evitar redundancias.

To begin with I added a function to round the doubles so that they do not appear so many decimals on the screen and the reading is easier for the user. The function is called "formatDecimals" and asks for two parameters which are the number to "format" and the number of decimals desired. For this converter I set the number to 3 decimal places.

This function is not my own, but I found it in a blog that explained several methods for rounding in java, the source is at the end of this post.

The next improvement is in the matter of reducing redundancy, since I was repeating a lot the lines of:

numberConverted = formatearDecimales(numberConverted, 3);
fieldTwo.setText(String.valueOf(numberConverted));

Then I decided to make a function that at the end applies the formatting of the double and the assignment of value to the field that reflects the conversion on the screen. However I ran into the problem that this should only be applied if one of the conditions was met, so I looked for a Python-style "finally" in Java and implemented the code in the function corresponding to each conversion.

This "finally" is based on relying on a boolean "doFinally" that will be false only if none of the conversion conditions are met, and then be filtered in an if that will allow to execute the formatting and assignment of text in the field only if "doFinally" is true (if any of the conditions were met). I found this method in StackOverFlow, the source is at the end of this post.

I also added a validation for the "-" character, because it is necessary to take it into account in the temperatures. This validation is in the numberValidator function. To avoid redundancies in the conversion of temperature and mass, I made a function called "fieldValidatorBasic" that includes the cases that are repeated in the three types of units.

The most obvious improvement, although I have already mentioned it indirectly, is the addition of the unit types: temperature and mass. The formulas are expressed in the functions "temp_unitConverter" and "weight_unitConverter", all with the aforementioned pseudo-finally to avoid redundancies.

JAVA SEPARATOR PSD FILE.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

JAVA SEPARATOR PSD FILE.png

Para la función que se encarga de las conversiones de masa las unidades disponibles son: Kilogramo, Gramo, Onza y Libra. Mientras que en temperatura son: Grados Celsius, Kelvin y Fahrenheit.

Para acceder a los nuevos tipos de unidades añadidos se toca alguno de los dos botones que están debajo de "convertir". Cada uno lleva a una nueva ventana similar a la anterior adaptada a las unidades de su tipo. Esto con la función "dispose".

Aparte de estas mejoras antes mencionadas se retiro una herencia mal aplicada en la clase "Control" y también una validación para el número de caracteres máximo, que quedó fijado en 11.

Y pues eso sería en resumen todo por esta actualización, como dije antes, no me centré en el aspecto visual tanto como quería, pero para la próxima versión si lo haré. También pienso añadir aun más unidades (quedó pendiente añadir más unidades de longitud extranjeras).

For the function that handles mass conversions the available units are: Kilogram, Gram, Ounce and Pound. The temperature units are: Degrees Celsius, Kelvin and Fahrenheit.

To access the new types of units added, touch one of the two buttons under "convert". Each one leads to a new window similar to the previous one adapted to the units of its type. This with the "dispose" function.

Apart from these improvements mentioned above, a wrongly applied inheritance in the "Control" class was removed and also a validation for the maximum number of characters, which was fixed at 11.

As I said before, I didn't focus on the visual aspect as much as I wanted to, but for the next version I will. I also plan to add even more units (it was pending to add more foreign length units).

JAVA SEPARATOR PSD FILE.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

JAVA SEPARATOR PSD FILE.png

record_000021.gif

JAVA SEPARATOR PSD FILE.png

Fuente de la función para redondear doubles

Fuente de la función equivalente a "finally" en Java

JAVA SEPARATOR PSD FILE.png


Redes actualizada.gif


Puedes seguirme por acá si lo deseas:
You can follow me here if you want:

Cuenta secundaria
(Dibujos, edición y juegos) | Secondary account (Drawings, editing and games)



0
0
0.000
2 comments
avatar

Genial, tengo desde hace mucho tiempo la intención de hacer algo grande como un asistente virtual con interfaz a modo de ayudante de casa y me he separado un poco de la programación para darle a la eléctronica tengo nivel tecnico superior en electronica, pero quiero hacer una licenciatura o ingenieria, espero seguir viendo mas contenido tuyo, como desde hace ya tiempo al igual contenido antiguo de ShadowMyst.

0
0
0.000
avatar

Brutaal, esas metas están geniales y esa idea también, la verdad es que no he llegado a hacer proyectos de esa magnitud, pero en el futuro me gustaría tener el nivel para emprender alguno que fuese tan visionario. Un obstáculo importante es el costo que puede llegar con dichos proyectos y también el tiempo necesario

0
0
0.000