elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Guía actualizada para evitar que un ransomware ataque tu empresa


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  GridBagLayout no posiciona los componentes
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: GridBagLayout no posiciona los componentes  (Leído 1,531 veces)
BJM

Desconectado Desconectado

Mensajes: 41


Ver Perfil
GridBagLayout no posiciona los componentes
« en: 26 Octubre 2016, 16:01 pm »

Dentro de la ventana Login los componentes se muestran totalmente desordenados, a pesar que estoy utilizando GridBagLayout

Código
  1. package drone;
  2.  
  3. import java.awt.*;
  4. import java.sql.*;
  5. import java.text.Collator;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8. import javax.swing.JOptionPane;
  9. import javax.swing.*;
  10.  
  11.  
  12.  
  13. public class Login extends javax.swing.JFrame {
  14. //private JPanel panel1;
  15. public static boolean RIGHT_TO_LEFT = false;
  16. final static boolean shouldFill = true;
  17. final static boolean shouldWeightX = true;
  18.  
  19.  
  20.    public Login() {
  21.        initComponents();
  22.        this.setSize(Toolkit.getDefaultToolkit().getScreenSize());
  23.        PnlFondo fondo = new PnlFondo();
  24.        this.setLayout(new BorderLayout());
  25.        this.add(fondo,BorderLayout.CENTER);
  26.        //getContentPane().setLayout(null);  
  27.        //addComponentsToPane(pane);
  28.    }
  29. public static void addComponentsToPane(Container pane) {
  30.        if (RIGHT_TO_LEFT) {
  31.            pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
  32.        }
  33.  
  34.        JLabel jLabel1,jLabel2,jLabel3;
  35.        JTextField usuario;
  36.        JPasswordField contraseña;
  37.        JButton jButton2;
  38.  
  39. pane.setLayout(new GridBagLayout());
  40. if (shouldFill) {
  41. //natural height, maximum width
  42. c.fill = GridBagConstraints.HORIZONTAL;
  43. }
  44.  
  45. jLabel1 = new JLabel();
  46. if (shouldWeightX) {
  47. c.weightx = 0.5;
  48. }
  49. c.fill = GridBagConstraints.HORIZONTAL;
  50. c.gridx = 200;
  51. c.gridy = 100;
  52. pane.add(jLabel1, c);
  53.  
  54. jLabel2 = new JLabel();
  55. c.fill = GridBagConstraints.HORIZONTAL;
  56. c.weightx = 0.5;
  57. c.gridx = 200;
  58. c.gridy = 110;
  59. pane.add(jLabel2, c);
  60.  
  61. jLabel3 = new JLabel();
  62. c.fill = GridBagConstraints.HORIZONTAL;
  63. c.weightx = 0.5;
  64. c.gridx = 2;
  65. c.gridy = 0;
  66. pane.add(jLabel3, c);
  67.  
  68. usuario = new JTextField("Long-Named Button 4");
  69. c.fill = GridBagConstraints.HORIZONTAL;
  70. c.ipady = 40;      //make this component tall
  71. c.weightx = 0.0;
  72. c.gridwidth = 3;
  73. c.gridx = 0;
  74. c.gridy = 1;
  75. pane.add(usuario, c);
  76.  
  77.        contraseña = new JPasswordField("Long-Named Button 4");
  78. c.fill = GridBagConstraints.HORIZONTAL;
  79. c.ipady = 40;      //make this component tall
  80. c.weightx = 0.0;
  81. c.gridwidth = 3;
  82. c.gridx = 0;
  83. c.gridy = 1;
  84. pane.add(contraseña, c);
  85.  
  86.  
  87. jButton2 = new JButton();
  88. c.fill = GridBagConstraints.HORIZONTAL;
  89. c.ipady = 0;       //reset to default
  90. c.weighty = 1.0;   //request any extra vertical space
  91. c.anchor = GridBagConstraints.PAGE_END; //bottom of space
  92. c.insets = new Insets(10,0,0,0);  //top padding
  93. c.gridx = 1;       //aligned with button 2
  94. c.gridwidth = 2;   //2 columns wide
  95. c.gridy = 2;       //third row
  96. pane.add(jButton2, c);
  97. }
  98.    private static void createAndShowGUI() {
  99.        //Create and set up the window.
  100.        JFrame frame = new JFrame("GridBagLayoutDemo");
  101.        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  102.  
  103.        //Set up the content pane.
  104.        addComponentsToPane(frame.getContentPane());
  105.  
  106.        //Display the window.
  107.        frame.pack();
  108.        frame.setVisible(true);
  109.    }
  110.  
  111.    /**
  112.      * This method is called from within the constructor to initialize the form.
  113.      * WARNING: Do NOT modify this code. The content of this method is always
  114.      * regenerated by the Form Editor.
  115.      */
  116.    @SuppressWarnings("unchecked")
  117.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  118.    private void initComponents() {
  119.  
  120.        jLabel1 = new javax.swing.JLabel();
  121.        jLabel2 = new javax.swing.JLabel();
  122.        usuario = new javax.swing.JTextField();
  123.        jLabel3 = new javax.swing.JLabel();
  124.        contraseña = new javax.swing.JPasswordField();
  125.        jButton2 = new javax.swing.JButton();
  126.  
  127.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  128.  
  129.        jLabel1.setText("Iniciar Sesion");
  130.  
  131.        jLabel2.setText("Usuario");
  132.  
  133.        jLabel3.setText("Contraseña");
  134.  
  135.        jButton2.setText("Aceptar");
  136.        jButton2.addActionListener(new java.awt.event.ActionListener() {
  137.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  138.                jButton2ActionPerformed(evt);
  139.            }
  140.        });
  141.  
  142.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  143.        getContentPane().setLayout(layout);
  144.        layout.setHorizontalGroup(
  145.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  146.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  147.                .addContainerGap(113, Short.MAX_VALUE)
  148.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
  149.                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  150.                        .addGroup(layout.createSequentialGroup()
  151.                            .addComponent(jLabel2)
  152.                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  153.                            .addComponent(usuario, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))
  154.                        .addGroup(layout.createSequentialGroup()
  155.                            .addGap(20, 20, 20)
  156.                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
  157.                            .addGap(169, 169, 169)))
  158.                    .addGroup(layout.createSequentialGroup()
  159.                        .addComponent(jLabel3)
  160.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  161.                        .addComponent(contraseña, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
  162.                        .addGap(163, 163, 163))))
  163.            .addGroup(layout.createSequentialGroup()
  164.                .addGap(148, 148, 148)
  165.                .addComponent(jButton2)
  166.                .addGap(0, 0, Short.MAX_VALUE))
  167.        );
  168.        layout.setVerticalGroup(
  169.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  170.            .addGroup(layout.createSequentialGroup()
  171.                .addContainerGap(108, Short.MAX_VALUE)
  172.                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
  173.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  174.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  175.                    .addComponent(jLabel2)
  176.                    .addComponent(usuario, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
  177.                .addGap(11, 11, 11)
  178.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  179.                    .addComponent(jLabel3)
  180.                    .addComponent(contraseña, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  181.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  182.                .addComponent(jButton2)
  183.                .addGap(107, 107, 107))
  184.        );
  185.  
  186.        pack();
  187.    }// </editor-fold>                        
  188.  
  189.    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  190.  
  191.        String user=usuario.getText();
  192.        String pass=contraseña.getText();
  193.        if ((user.length()==0)||(pass.length()==0)){
  194.           JOptionPane.showMessageDialog(rootPane, "Campo usuario o contraseña vacio");
  195.             }else{
  196.            Conexion mysql= new Conexion();
  197.       Connection conn= mysql.conectar();
  198.      /* if(conn!=null){
  199.            JOptionPane.showMessageDialog(rootPane, "Conexion con base de datos");
  200.        }*/
  201.              try {
  202.                  @SuppressWarnings("null")
  203.                  Statement sentencia= conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
  204.                ResultSet rs;
  205.                rs = sentencia.executeQuery("SELECT * FROM usuarios WHERE Usuario='"+user+"' && Contraseña='"+pass+"'");
  206.                Collator comparador = Collator.getInstance();
  207.                comparador.setStrength(Collator.TERTIARY);
  208.                String tem1=rs.getString("Usuario");
  209.                String tem2=rs.getString("Contraseña");
  210.                if(rs.next()&&comparador.equals(user,tem1)&&comparador.equals(pass,tem2)){
  211.                    Menu inicio=new Menu();
  212.                    inicio.setVisible(true);
  213.                }
  214.                else{
  215.                    JOptionPane.showMessageDialog(rootPane, "Los datos son incorrectos");
  216.                }
  217.            } catch (SQLException ex) {
  218.                Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
  219.            }
  220.        }
  221.        //if (user.equals()&&pass.equals());
  222.    }                                        
  223.  
  224.    /**
  225.      * @param args the command line arguments
  226.      */
  227.    public static void main(String args[]) {
  228.        /* Set the Nimbus look and feel */
  229.        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  230.        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  231.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  232.          */
  233.        try {
  234.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  235.                if ("Nimbus".equals(info.getName())) {
  236.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  237.                    break;
  238.                }
  239.            }
  240.        } catch (ClassNotFoundException ex) {
  241.            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  242.        } catch (InstantiationException ex) {
  243.            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  244.        } catch (IllegalAccessException ex) {
  245.            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  246.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  247.            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  248.        }
  249.        //</editor-fold>
  250.  
  251.        /* Create and display the form */
  252.        java.awt.EventQueue.invokeLater(new Runnable() {
  253.            public void run() {
  254.                createAndShowGUI();
  255.                new Login().setVisible(true);
  256.            }
  257.        });
  258.  
  259.    }
  260.  
  261.    // Variables declaration - do not modify                    
  262.    private javax.swing.JPasswordField contraseña;
  263.    private javax.swing.JButton jButton2;
  264.    private javax.swing.JLabel jLabel1;
  265.    private javax.swing.JLabel jLabel2;
  266.    private javax.swing.JLabel jLabel3;
  267.    private javax.swing.JTextField usuario;
  268.    // End of variables declaration                  
  269. }
  270.  

A quien pueda ayudar, gracias por adelentado


En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Problemas con JInternalFrame y GridBagLayout
Java
Kuni 7 5,878 Último mensaje 21 Mayo 2007, 01:03 am
por Kuni
Problema de resize con GridBagLayout
Java
undercode2 0 1,765 Último mensaje 19 Noviembre 2011, 23:08 pm
por undercode2
Actualizar componentes? Repintar componenteS??
Java
ChicoTolerante 2 2,400 Último mensaje 27 Febrero 2013, 10:54 am
por ChicoTolerante
Confusión con el gestor GridBagLayout
Java
marixxaa 1 1,767 Último mensaje 21 Enero 2016, 00:09 am
por 0xFer
GridBagLayout « 1 2 »
Java
Baal_30 10 5,849 Último mensaje 21 Mayo 2016, 17:50 pm
por + 1 Oculto(s)
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines