How to show in jframe the results of the sql statement?

0

I would like to know what I am doing wrong in the code, it turns out that I try to get the data of the statement in the JFrame . I leave the code what I have

package Formulario;


import Formulario.Menu;
import Clases.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Login extends javax.swing.JFrame {

   public static Controlador controller;
   public static ResultSet rs;

    public Login() {
        initComponents();
    }

    /**
     * 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")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btIngresar = new javax.swing.JButton();
        tfUsuario = new javax.swing.JTextField();
        lbMsj = new javax.swing.JLabel();
        psPSW = new javax.swing.JPasswordField();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText(" Usuario :");

        jLabel2.setText("Clave :");

        btIngresar.setText("INGRESAR");
        btIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btIngresarActionPerformed(evt);
            }
        });

        tfUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfUsuarioActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel3.setText("Sistema de Inventario de Activos Fijos");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(91, 91, 91)
                .addComponent(lbMsj, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btIngresar)
                .addGap(45, 45, 45))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(66, 66, 66)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(tfUsuario)
                            .addComponent(psPSW, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jLabel3))
                .addContainerGap(68, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jLabel3)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(138, 138, 138)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(tfUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(psPSW, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbMsj, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btIngresar)
                        .addGap(30, 30, 30))))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(58, 58, 58)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(142, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void tfUsuarioActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
    }                                         

    private void btIngresarActionPerformed(java.awt.event.ActionEvent evt) {                                           

        String Passw = new String(psPSW.getPassword());
        try{
            controller =new Controlador();
            controller.crearConexion();
           }catch (SQLException ex){

               Logger.getLogger(Login.class.getName()).
               log(Level.SEVERE, null, ex);
               }

        String sql="Select * from Usuario WHERE Us_Nom='"+tfUsuario.getText()+"' and Us_Pwd='"+Passw+"'";
            try {
                 rs=controller.mandarQUERY(sql);
            while (rs.next()){

                    Menu vent= new Menu();
                    vent.setVisible(true);
                    this.setVisible(false);
                    }
                } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).
            log(Level.SEVERE, null, ex);
            }
    }                                          

    /**
     * @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 ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btIngresar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lbMsj;
    private javax.swing.JPasswordField psPSW;
    private javax.swing.JTextField tfUsuario;
    // End of variables declaration                   
}
    
asked by Programador noob 25.06.2016 в 02:16
source

3 answers

1
 String nombreUsuario=null;
 Menu mnVista;
 while (rs.next()){
  nombreUsuario=rs.getString(0); //ejemplo
 }
mnVista=new mnVista(nombreUsuario);//opcion 1 pase por constructor
mnVista.jLabel1.setText(nombreUsuario);// componente static

These are some suggestions adapting to what you have code, because it may not be the most optimal

    
answered by 26.06.2016 в 09:23
1

To show the result of an SQL statement, it is usually best to display it using a JTable .

You define a JTable with the number of columns equal to the number of fields you want to be shown in the result of the select and without rows.

Inside the loop you have:

while(rs.next){
...
}

You increase the size of the JTable while there are records and you assign each column the value you want

    
answered by 29.06.2016 в 13:14
0

I will give you two good practices when working with Swing / JavaFX.

  • Use the VO pattern to map your tables to objects.
  • Take advantage of the generic classes of controls in Swing whenever you can.
  • Never mix business logic with views.
  • Use the VO pattern

    It is highly recommended to use the VO pattern when working with databases. When you map a table to an object, you encapsulate all this information in Java objects, so that you can access information in a clear, clean and concise way.

    while(rs.next()) {
        Persona persona = new Persona();
        persona.setNombre(rs.getString("nombre"));
        persona.setApellido(rs.getString("apellido"));
        persona.setDireccion(rs.getString("direccion"));
        persona.setTelefono(rs.getString("telefono"));
    }
    

    Take advantage of generic Swing / JavaFX classes

    In JTable there is no way to use Generics because no JTable is not generic, however you can do it by doing DefaultTableModel . However, in some controls such as JList or JComboBox it is possible to associate a certain type of data that can be an object to the control.

    To show a List of objects in your JTable, it's easier to use the VO pattern.

    DefaultTableModel model = (DefaultTableModel) tblPersonas.getModel();
    for(Persona persona : personas) {
      model.addRow(new Object[] {
        persona.getNombre(),
        persona.getApellido(),
        persona.getDireccion(),
        persona.getTelefono()
      });
    }
    

    Never mix business code with views

    This is perhaps the most important point of the three. Mixing business code with views is declaring your application to imminent failure . An application that does not establish layers simply can not scale (grow in the future, adding functionality). In addition, there will come a point where is torture to keep it , because everything is tangled. A real tangle.

    Links of interest:

    answered by 29.06.2016 в 14:17