0% encontró este documento útil (0 votos)
7 vistas8 páginas

Interfaces de Usuario en Java: Mercadito

Este programa desarrolla una interfaz gráfica de usuario en Java para un mercado virtual que permite seleccionar productos, ingresar cantidades, calcular subtotales y mostrar un reporte de compras.
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
7 vistas8 páginas

Interfaces de Usuario en Java: Mercadito

Este programa desarrolla una interfaz gráfica de usuario en Java para un mercado virtual que permite seleccionar productos, ingresar cantidades, calcular subtotales y mostrar un reporte de compras.
Derechos de autor
© All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd

Universidad Autónoma del Estado de Hidalgo

Área Académica de Matemáticas y Física


Licenciatura en Física y Tecnología Avanzada

Programación orientada a objetos en entorno unix

Actividad 3.2:
Interfaces de usuario en Java - Mercadito

Jorge Luis Moreno Sánchez 440593


Grupo 6°1

Professor:
Mtra. Karla I. López de la Cruz

May 12, 2023

1
Programación estructurada en entorno unix. Interfaces de usuario en Java

1 Funcionamiento del programa


1.1 jFrame Mercado
1.1.1 Código

1 package mercado ;
2
3 import java . awt . Color ;
4 import java . time . LocalDateTime ;
5 import java . time . format . DateT imeForma tter ;
6

7 /* *
8 *
9 * @author jorge
10 */
11 public class Mercado extends javax . swing . JFrame {
12

13 /* *
14 * Creates new form Mercado
15 */
16 // Manzanas - Zanahorias - Arroz - Lentejas - Carne molida - Mole en polvo
17 private double [] prices = new double []{27 ,15 ,37 ,42 ,18 ,20};
18 private double cantidad , total = 0;
19
20 private String aux = " " ;
21
22
23 public Mercado () {
24 initComponents () ;
25 jTextField3 . setText ( String . format ( " %.2 f " , prices [ jComboBox1 .
getSelectedIndex () ]) ) ;
26 }
27
28 /* *
29 * This method is called from within the constructor to initialize the form .
30 * WARNING : Do NOT modify this code . The content of this method is always
31 * regenerated by the Form Editor .
32 */
33 @Sup pressWarn ings ( " unchecked " )
34 // < editor - fold defaultstate =" collapsed " desc =" Generated Code " >
35 private void initComponents () ;
36
37
38
39 private void j T e x t F i e l d 2 F o c u s G a i n e d ( java . awt . event . FocusEvent evt ) {
40 // TODO add your handling code here :
41 jTextField2 . selectAll () ;
42 }
43
44 private void j C o m b o B o x 1 A c t i o n P e r f o r m e d ( java . awt . event . ActionEvent evt ) {
45 // TODO add your handling code here :
46 jTextField2 . requestFocus () ;
47 jTextField3 . setText ( String . format ( " %.2 f " , prices [ jComboBox1 .
getSelectedIndex () ]) ) ;

LiFTA 2 de 8 UAEH
Programación estructurada en entorno unix. Interfaces de usuario en Java

48 }
49
50 private void j T e x t F i e l d 2 K e y R e l e a s e d ( java . awt . event . KeyEvent evt ) {
51 // TODO add your handling code here :
52 if ( StrIsNumber ( jTextField2 . getText () ) ) {
53 jTextField4 . setText ( String . format ( " %.2 f " , Double . parseDouble (
jTextField2 . getText () ) * prices [ jComboBox1 . getSelectedIndex () ]) ) ;
54 cantidad = Double . parseDouble ( jTextField2 . getText () ) ;
55 }
56 }
57

58 private void j B u t t o n 1 A c t i o n P e r f o r m e d ( java . awt . event . ActionEvent evt ) {


59 // agregar
60 if ( StrIsNumber ( jTextField4 . getText () ) ) {
61 if ( Double . parseDouble ( jTextField4 . getText () ) >0) {
62 LocalDateTime date = LocalDateTime . now () ;
63 Date TimeForma tter datef = DateTime Formatte r . ofPattern ( " dd - MM - yyyy
- HH : mm : ss " ) ;
64 if ( jTextField1 . getText () . equals ( " " ) ) {
65 jTextField1 . setText ( " --" ) ;
66 }
67 aux = aux + " Art í culo \ tPrecio ( kg ) \ tCantidad \ tSubtotal \ n " ;
68 aux = aux + jComboBox1 . getSelectedItem () + " \ t$ " + String . format ( " %.2 f "
, prices [ jComboBox1 . getSelectedIndex () ]) ;
69 aux = aux + " \ t " + String . valueOf ( cantidad ) + " kg \ t$ " + jTextField4 .
getText () + " \ n " ;
70 jTextArea1 . setText ( " JoluMercado \ n " + date . format ( datef ) + " \ n \ n " + aux )
;
71 jTextArea1 . setBackground ( new Color (156 ,181 ,171) ) ;
72 jTextField1 . setBackground ( new Color (156 ,181 ,171) ) ;
73 total += Double . parseDouble ( jTextField4 . getText () ) ;
74 }
75 }
76 }
77
78 private void j B u t t o n 3 A c t i o n P e r f o r m e d ( java . awt . event . ActionEvent evt ) {
79 // salir
80 aux = " " ;
81 total = 0;
82 jTextArea1 . setText ( " " ) ;
83 jTextField1 . setText ( " " ) ;
84 jTextField2 . setText ( " --" ) ;
85 jTextField4 . setText ( " --" ) ;
86 jTextArea1 . setBackground ( new Color (111 ,136 ,123) ) ;
87 jTextField1 . setBackground ( new Color (111 ,136 ,123) ) ;
88 }
89
90 private void j B u t t o n 2 A c t i o n P e r f o r m e d ( java . awt . event . ActionEvent evt ) {
91 // TODO add your handling code here :
92 if ( total != 0) {
93 jTextField1 . setText ( " $ " + String . valueOf ( total ) ) ;
94 aux = " " ;
95 total = 0;
96 }
97 }
98

LiFTA 3 de 8 UAEH
Programación estructurada en entorno unix. Interfaces de usuario en Java

99 private static boolean StrIsNumber ( String a ) {


100 try {
101 Double . parseDouble ( a ) ;
102 return true ;
103 } catch ( N u m b e r F o r m a t E x c e p t i o n e ) {
104 return false ;
105 }
106
107 }
108
109 /* *
110 * @param args the command line arguments
111 */
112 public static void main ( String args []) {
113 /* Set the Nimbus look and feel */
114 // < editor - fold defaultstate =" collapsed " desc =" Look and feel setting code
( optional ) " >
115 /* If Nimbus ( introduced in Java SE 6) is not available , stay with the
default look and feel .
116 * For details see http :// download . oracle . com / javase / tutorial / uiswing /
lookandfeel / plaf . html
117 */
118 try {
119 for ( javax . swing . UIManager . LookAndFeelInfo info : javax . swing .
UIManager . g e t I n s t a l l e d L o o k A n d F e e l s () ) {
120 if ( " Nimbus " . equals ( info . getName () ) ) {
121 javax . swing . UIManager . setLookAndFeel ( info . getClassName () ) ;
122 break ;
123 }
124 }
125 } catch ( C l a s s N o t F o u n d E x c e p t i o n ex ) {
126 java . util . logging . Logger . getLogger ( Mercado . class . getName () ) . log ( java .
util . logging . Level . SEVERE , null , ex ) ;
127 } catch ( I n s t a n t i a t i o n E x c e p t i o n ex ) {
128 java . util . logging . Logger . getLogger ( Mercado . class . getName () ) . log ( java .
util . logging . Level . SEVERE , null , ex ) ;
129 } catch ( I l l e g a l A c c e s s E x c e p t i o n ex ) {
130 java . util . logging . Logger . getLogger ( Mercado . class . getName () ) . log ( java .
util . logging . Level . SEVERE , null , ex ) ;
131 } catch ( javax . swing . U n s u p p o r t e d L o o k A n d F e e l E x c e p t i o n ex ) {
132 java . util . logging . Logger . getLogger ( Mercado . class . getName () ) . log ( java .
util . logging . Level . SEVERE , null , ex ) ;
133 }
134 // </ editor - fold >
135

136 /* Create and display the form */


137 java . awt . EventQueue . invokeLater ( new Runnable () {
138 public void run () {
139 new Mercado () . setVisible ( true ) ;
140 }
141 }) ;
142 }
143
144 // Variables declaration - do not modify
145 private javax . swing . JButton jButton1 ;
146 private javax . swing . JButton jButton2 ;

LiFTA 4 de 8 UAEH
Programación estructurada en entorno unix. Interfaces de usuario en Java

147 private javax . swing . JButton jButton3 ;


148 private javax . swing . JComboBox < String > jComboBox1 ;
149 private javax . swing . JLabel jLabel1 ;
150 private javax . swing . JLabel jLabel2 ;
151 private javax . swing . JLabel jLabel3 ;
152 private javax . swing . JLabel jLabel4 ;
153 private javax . swing . JLabel jLabel5 ;
154 private javax . swing . JLabel jLabel6 ;
155 private javax . swing . JLabel jLabel7 ;
156 private javax . swing . JLabel jLabel8 ;
157 private javax . swing . JPanel jPanel1 ;
158 private javax . swing . JPanel jPanel2 ;
159 private javax . swing . JPanel jPanel3 ;
160 private javax . swing . JPanel jPanel7 ;
161 private javax . swing . JScrollPane jScrollPane1 ;
162 private javax . swing . JTextArea jTextArea1 ;
163 private javax . swing . JTextField jTextField1 ;
164 private javax . swing . JTextField jTextField2 ;
165 private javax . swing . JTextField jTextField3 ;
166 private javax . swing . JTextField jTextField4 ;
167 // End of variables declaration
168 }

1.1.2 Explicación
Se declara una variable arreglo de tipo double que almacena los precios para cada "ítem" en la tienda,
dos variables de tipo double de control para almacenar precios, y una variable de tipo string para
almacenar el texto a imprimir.

Se declara una función de apoyo cuyo argumento es una String, y utiliza try para comprobar si
la string puede ser convertida a una variable de tipo Double, y se llama StrIsNumber.

El jTextArea que muestra la lista de productos ordenados, y el jTextField del subtotal están
inicialmente en un estado "apagado", que no se va a "encender" hasta agregar alguna cantidad de
un producto.

Cuando se selecciona un ítem del jComboBox, mueve el cursor del usuario al jTextField que tiene
la cantidad de producto como entrada, utilizando la función requestFocus, así como actualizar el
precio del producto en el jTextField que tiene de salida el precio del producto por kilo.

Cuando el cursor entra en el jTextField con la cantidad del producto, selecciona todo el texto para
su modificación, y cuando éste es modificado, comprueba si es un Double con StrIsNumber, actualiza
el jTextField con salida del subtotal multiplicando el valor del precio del producto seleccionado por
su cantidad.

Una vez se pulse el jButton de agregar un producto, en caso de que el subtotal sea válido,
jTextArea va a imprimir el nombre del mercado, la fecha y hora actuales utilizando la librería Lo-
calDateTime, los encabezados de "Artículo", "Precio", "Cantidad" y "Subtotal", y utilizando la
variable aux, se van acumulando los productos ordenados, con su cantidad y subtotal, y la variable
de control "total" va sumando el subtotal acumulado.

LiFTA 5 de 8 UAEH
Programación estructurada en entorno unix. Interfaces de usuario en Java

Cuando se presione el jButton de imprimir, se va a imprimir la variable de control "total", y se


vaciarán los valores de las variables "total" y "aux", para que cuando se agreguen más productos
éstos se impriman en otra lista sin seguirse acumulando.

Si se presiona el jButton de apagar, éste va a colocar el jTextArea y el jTextField del total vacíos
y en estado "apagados" de nuevo.

2 Capturas de ejecución

LiFTA 6 de 8 UAEH
Programación estructurada en entorno unix. Interfaces de usuario en Java

LiFTA 7 de 8 UAEH
Programación estructurada en entorno unix. Interfaces de usuario en Java

References
[1] Deitel, P. J., & Deitel, H. M. (2012). Java cómo programar (10ma ed.). Pearson Educación.

[2] Schildt, H. (2019). Java: The complete reference, 12th edition. McGraw-Hill Education.

[3] Farrell, J. (2014). Java Programming, 8th edition. Cengage Learning.

[4] Schildt, H. (2014). Java: A beginner’s guide, Eighth edition. McGraw-Hill Education.

LiFTA 8 de 8 UAEH

Common questions

Con tecnología de IA

The program employs a `try-catch` mechanism in the `StrIsNumber` function to handle potential `NumberFormatException` errors. This method effectively safeguards against attempts to parse invalid numerical input, thereby maintaining program stability by preventing crashes due to incorrect input formats. By catching exceptions, the program enhances robustness in user input validation .

The `jButton2ActionPerformed` method is executed when the user clicks the button assigned to finalize or confirm the accumulated total of the order. It checks whether the `total` is non-zero, updates the respective `jTextField` to display the total amount, and resets the `aux` and `total` variables to start fresh for any new orders .

`initComponents` is crucial for setting up the user interface initially by configuring and organizing all graphical elements like buttons, fields, and panels. This method is called within the constructor, ensuring components are initialized before any user interaction begins, which promotes stability and ensures that all UI elements are properly positioned and functional .

The `StrIsNumber` function serves to validate whether a given string can be converted into a `Double` type number. It uses a `try-catch` block to attempt parsing the string as a double; if successful, it returns true, indicating the string is a valid number. This function is crucial for ensuring only numerical inputs are processed in calculations, like updating prices and totals in the `jTextField` for the subtotal .

When the 'add product' button is pressed, provided that the subtotal is valid, the program records the details of the transaction: the product name, unit price, quantity, and the calculated subtotal are appended to the `jTextArea1`. Additionally, the `total` variable accumulates these subtotals, updating the overarching total for the session. These actions facilitate seamless order tracking and totaling within the user interface .

Upon pressing the print button, the program outputs the accumulated subtotal, stored in the variable `total`, to the user interface. It formats this display with the current date and time, retrieved using the `LocalDateTime` library, and includes headers for 'Artículo', 'Precio', 'Cantidad', and 'Subtotal'. The program then clears the `total` and `aux` variables, resetting the order for subsequent entries .

After confirming an order by printing the total, the program employs a reset strategy for input fields by setting fields such as `jTextField2` and `jTextField4` to placeholder values like `"--"`. Additionally, it clears the `jTextArea1` and `jTextField1` to prepare for new input, signaling the user that the interface is ready for the next session .

The program sets specific color values for UI components to maintain a consistent aesthetic theme. For example, `jTextArea1` and `jTextField1` are set to colors like (156, 181, 171) when displaying the order, signaling active state, and (111, 136, 123) upon resetting or deactivating them, indicating availability for new entries. This visual consistency aids user experience by providing intuitive cues about the component's statuses .

When a user selects an item from the `jComboBox`, the program requests focus on the `jTextField` that collects the product quantity, ensuring the user is positioned to input the desired amount. Simultaneously, it updates the `jTextField` displaying the price per kilogram of the selected item, fetched from the `prices` array using the selected index .

The `Nimbus` look and feel is utilized to provide a modern and consistent graphical appearance in Java applications. By leveraging Nimbus, the program aligns with contemporary UI design standards, which prioritize sleek aesthetics and intuitive user interactions. It enhances the visual appeal and usability of the application, making it more attractive and efficient for users, which is crucial in designing competitive software interfaces .

También podría gustarte