es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Estoy obteniendo todo tipo de errores con este código. ¿Estoy colocando correctamente el try/catch o mi código está completamente desordenado?

Estoy intentando crear una ventana emergente que registre depósitos y retiros de una cuenta bancaria. Tengo la ventana creada correctamente, pero estoy recibiendo un montón de errores cuando intento crear el código para hacer las operaciones matemáticas para los dos botones. Estoy bastante seguro de que simplemente estoy ingresando el código en el lugar equivocado, pero no estoy seguro de cómo arreglarlo. Este es el código que tengo actualmente. ¿Alguien puede explicarme qué hice mal?


import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.LayoutStyle.ComponentPlacement; import java.awt.Font; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class acmeBank { private JFrame frame; private JTextField creditInput; private JTextField debitInput; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { acmeBank window = new acmeBank(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public acmeBank() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { double balance = 0; frame = new JFrame(); frame.setBounds(100, 100, 470, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel lblNewLabel = new JLabel("DEPOSITO"); lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 14)); JLabel lblNewLabel_1 = new JLabel("RETIRO"); lblNewLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 14)); creditInput = new JTextField(); creditInput.setColumns(10); debitInput = new JTextField(); debitInput.setColumns(10); JButton creditButton = new JButton("DEPOSITAR"); creditButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); JButton debitButton = new JButton("RETIRAR"); debitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); JButton clearButton = new JButton("LIMPIAR"); clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); JLabel lblNewLabel_2 = new JLabel("BALANCE $"); lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 14)); JLabel totalBalance = new JLabel(""); GroupLayout groupLayout = new GroupLayout(frame.getContentPane()); groupLayout.setHorizontalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false) .addGroup(groupLayout.createSequentialGroup() .addGap(47) .addComponent(lblNewLabel_2) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(totalBalance, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(Alignment.LEADING, groupLayout.createSequentialGroup() .addGap(18) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(lblNewLabel, Alignment.TRAILING) .addComponent(lblNewLabel_1, Alignment.TRAILING)) .addGap(0) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false) .addComponent(debitInput, Alignment.TRAILING) .addComponent(creditInput, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)))) .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(debitButton, GroupLayout.PREFERRED_SIZE, 76, GroupLayout.PREFERRED_SIZE) .addComponent(creditButton, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE)) .addGap(18) .addComponent(clearButton, GroupLayout.PREFERRED_SIZE, 78, GroupLayout.PREFERRED_SIZE) .addContainerGap(39, Short.MAX_VALUE)) ); groupLayout.setVerticalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addGroup(groupLayout.createParallelGroup(Alignment.LEADING) .addGroup(groupLayout.createSequentialGroup() .addGap(23) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE) .addComponent(lblNewLabel) .addComponent(creditInput, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(creditButton)) .addGap(11) .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE) .addComponent(lblNewLabel_1) .addComponent(debitInput, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(debitButton))) .addGroup(groupLayout.createSequentialGroup() .addGap(40) .addComponent(clearButton))) .addGap(33) .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING) .addComponent(lblNewLabel_2) .addComponent(totalBalance, GroupLayout.PREFERRED_SIZE, 26, GroupLayout.PREFERRED_SIZE)) .addContainerGap(122, Short.MAX_VALUE)) ); frame.getContentPane().setLayout(groupLayout); public void actionPerformed(ActionEvent e) { if (e.getSource() == creditButton) { try { double amount = Double.parseDouble(creditInput.getText()); balance += amount; totalBalance.setText("$" + balance); } catch (NumberFormatException ee) { JOptionPane.showMessageDialog(f, "Por favor ingrese solo números"); } } else if (e.getSource() == debitButton) { try { double amount = Double.parseDouble(debitInput.getText()); balance -= amount; totalBalance.setText("$" + balance); } catch (NumberFormatException ee) { JOptionPane.showMessageDialog(f, "Por favor ingrese solo números"); } } else if (e.getSource() == clearButton) { debitInput.setText(""); creditInput.setText(""); } } public static void main(String[] args) { new ACMEBank(); } } }
Tags:  , , ,

Answer

  1. Avatar for davy.ai

    El problema es que el método actionPerformed, que es responsable de realizar los cálculos y actualizar el equilibrio, se encuentra dentro del método initialize, que solo se encarga de configurar los componentes GUI.

    Para solucionar este problema, debes mover el método actionPerformed fuera del método initialize y dentro de la clase acmeBank. Dentro del método actionPerformed, debes actualizar la variable double balance para reflejar los cambios en el saldo de la cuenta, y actualizar la etiqueta totalBalance con el nuevo saldo.

    Aquí hay un ejemplo de cómo puedes actualizar el método actionPerformed:

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == creditButton) {
            try {
                double amount = Double.parseDouble(creditInput.getText());
                balance += amount;
                totalBalance.setText("$" + balance);
            } catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(frame, "Ingrese solo números");
            }
        } else if (e.getSource() == debitButton) {
            try {
                double amount = Double.parseDouble(debitInput.getText());
                balance -= amount;
                totalBalance.setText("$" + balance);
            } catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(frame, "Ingrese solo números");
            }
        } else if (e.getSource() == clearButton) {
            debitInput.setText("");
            creditInput.setText("");
            balance = 0;
            totalBalance.setText("");
        }
    }
    

    En este ejemplo, agregamos un bloque try-catch para capturar cualquier NumberFormatException que pueda ocurrir cuando el usuario ingresa una entrada no válida. Luego actualizamos la variable balance en consecuencia y actualizamos la etiqueta totalBalance con el nuevo saldo.

    Finalmente, agregamos una verificación para cuando el usuario hace clic en el botón clearButton, que borra los campos de entrada y restablece el saldo a 0.

Comments are closed.