identifica el error del siguiente codigo por que no me compila inplementa uno corregido:…
- User
identifica el error del siguiente codigo por que no me compila inplementa uno corregido: package VentanaEntrega;
import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTextField;
public class VentanaEntrega extends JFrame { private JTextField txtDireccion; private JButton btnEfectivo, btnTarjeta;
public VentanaEntrega(double total) { setTitle("Ingrese la dirección de entrega"); setSize(300, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new FlowLayout()); txtDireccion = new JTextField(20); btnEfectivo = new JButton("Efectivo"); btnTarjeta = new JButton("Tarjeta"); btnEfectivo.addActionListener(e -> { JOptionPane.showMessageDialog(this, "Total a pagar: " + total); }); add(new JLabel("Dirección de entrega:")); add(txtDireccion); add(btnEfectivo); add(btnTarjeta); }} /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") //
private void initComponents() {setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); pack(); }// </editor-fold> /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VentanaEntrega.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new VentanaEntrega().setVisible(true); } }); } // Variables declaration - do not modify // End of variables declaration - Assistant
Tu código presenta varios problemas que impiden que compile correctamente. Aquí están las correcciones que se deben hacer para que funcione:
-
Falta la importación de
JOptionPaneyJLabel: Estás usandoJOptionPanepara mostrar un cuadro de diálogo, pero no lo has importado. También estás usandoJLabelpara mostrar el texto de la dirección, pero igualmente no lo has importado. -
El constructor de
VentanaEntregano coincide con la llamada enmain: Estás tratando de crear una instancia deVentanaEntrega()sin parámetros, pero el constructor está definido para recibir undouble total. Deberías pasar un valor al constructor. -
No se está configurando correctamente el frame al final de su inicialización. Debes añadir un
setVisible(true)y asegurarte de que se inicialice correctamente.
Aquí tienes el código corregido:
package VentanaEntrega; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JLabel; import javax.swing.JTextField; public class VentanaEntrega extends JFrame { private JTextField txtDireccion; private JButton btnEfectivo, btnTarjeta; public VentanaEntrega(double total) { setTitle("Ingrese la dirección de entrega"); setSize(300, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new FlowLayout()); txtDireccion = new JTextField(20); btnEfectivo = new JButton("Efectivo"); btnTarjeta = new JButton("Tarjeta"); btnEfectivo.addActionListener(e -> { JOptionPane.showMessageDialog(this, "Total a pagar: " + total); }); // Agregar JLabel que no estaba importado add(new JLabel("Dirección de entrega:")); add(txtDireccion); add(btnEfectivo); add(btnTarjeta); // Hacer visible la ventana setVisible(true); } public static void main(String[] args) { // Aquí pasamos un valor al constructor double total = 100.0; // Cambia este valor según necesites java.awt.EventQueue.invokeLater(() -> { new VentanaEntrega(total); }); } }Cambios realizados:
- Importaciones necesarias: Se agregó
import javax.swing.JOptionPane;yimport javax.swing.JLabel;. - Llamada al constructor: En
main, se especifica un valor predeterminado paratotalal crear una nueva instancia deVentanaEntrega. - Hacer visible el JFrame recién creado se hace dentro del constructor después de añadir los componentes.
Ahora el código debería compilar y ejecutar sin problemas.
-
- User
implementa el codigo corregido
- Assistant
Claro, aquí tienes el código completo y corregido de la clase
VentanaEntrega, que compila y ejecuta correctamente:package VentanaEntrega; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JLabel; import javax.swing.JTextField; public class VentanaEntrega extends JFrame { private JTextField txtDireccion; private JButton btnEfectivo, btnTarjeta; public VentanaEntrega(double total) { setTitle("Ingrese la dirección de entrega"); setSize(300, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new FlowLayout()); txtDireccion = new JTextField(20); btnEfectivo = new JButton("Efectivo"); btnTarjeta = new JButton("Tarjeta"); btnEfectivo.addActionListener(e -> { JOptionPane.showMessageDialog(this, "Total a pagar: " + total); }); // Etiqueta para la dirección de entrega add(new JLabel("Dirección de entrega:")); add(txtDireccion); add(btnEfectivo); add(btnTarjeta); // Hacer visible la ventana setVisible(true); } public static void main(String[] args) { // Aquí pasamos un valor al constructor double total = 100.0; // Cambia este valor según necesites java.awt.EventQueue.invokeLater(() -> { new VentanaEntrega(total); }); } }Descripción del código:
-
Importaciones: Se importan las clases necesarias de
javax.swingyjava.awt. -
Constructor
VentanaEntrega: Configura la ventana principal, posicionando sus componentes (JTextField, JButton y JLabel). Se añade unActionListeneral botón "Efectivo" que muestra un cuadro de diálogo con el total a pagar cuando se presiona. -
Método
main: Se define un valor paratotaly se crea una instancia de la ventana en el hilo de eventos de Swing para garantizar que la GUI se ejecute correctamente en un hilo separado.
Cómo ejecutar el código:
- Guarda este código en un archivo llamado
VentanaEntrega.javadentro del paqueteVentanaEntrega. - Asegúrate de tener configurado tu entorno de desarrollo de Java (como Eclipse, IntelliJ IDEA o un simple entorno de línea de comando).
- Compila y ejecuta el archivo. Deberías ver una ventana con un campo de texto para ingresar la dirección y dos botones: "Efectivo" y "Tarjeta". Al hacer clic en el botón "Efectivo", se mostrará un cuadro de diálogo con el total a pagar.
-