2009-08-14 17 views

Respuesta

19

Debe agregar al menos un componente que llene el espacio horizontal. Si usted no tiene un componente de este tipo puede probar esto:

GridBagConstraints noFill = new GridBagConstraints(); 
noFill.anchor = GridBagConstraints.WEST; 
noFill.fill = GridBagConstraints.NONE; 

GridBagConstraints horizontalFill = new GridBagConstraints(); 
horizontalFill.anchor = GridBagConstraints.WEST; 
horizontalFill.fill = GridBagConstraints.HORIZONTAL;  

panel.add(new JLabel("Left Aligned"), noFill); 
panel.add(Box.createHorizontalGlue(), horizontalFill); 
0

Si desea cambiar el lugar donde un componente se encuentra en una célula creada por un GridBagLayout utilizar el parámetro de anchorGridBagConstraints.

+0

No es suficiente, debe tener un componente que ocupe el espacio horizontal restante. –

+0

sí, yo sé eso; esa no es la pregunta, el problema está en poner toda esta 'cuadrícula' en la esquina superior izquierda de JPanel, que contiene elementos, sin interferir con el trabajo interior de los Cuadros de Grid de diseñar componentes. Solo para decirle a GridBag: bueno, chico, haz tu trabajo como quieras, solo siéntate en la esquina superior izquierda en lugar de sentarte en el centro –

+1

@as: Bombe tiene razón en que necesitas usar el GridBagConstraints.anchor, solo eché de menos lo de el componente de relleno. Creo que estoy en lo cierto al decir que GridBagLayout no respeta JComponent.setAlignmentX y JComponent.setAlignmentY, que se aplican al componente en sí, no al contenido de un contenedor. –

0

Tuve el mismo problema que tú. Lo resolvió agregando ese Panel a otro con restricciones de BorderLayout y NORTH.

Ondrej

0

Usted puede hacer que simplemente utilizar este frasco utilidad painless-gridbag. También hacer que su código con GridBagLayout mucho más bonita, como seguir

PainlessGridBag gbl = new PainlessGridBag(getContentPane(), false); 

    gbl.row().cell(lblFirstName).cell(txtFirstName).fillX() 
      .cell(lblFamilyName).cell(txtFamilyName).fillX(); 
    gbl.row().cell(lblAddress).cellXRemainder(txtAddress).fillX(); 

    gbl.doneAndPushEverythingToTop(); 
+0

-1 Sustituyendo un dolor por otro. Es mucho más útil aprender GridBagLayout. –

8

Además de establecer los campos anchor y fill, es probable que necesite para establecer el campo weightx. Esto ayuda a especificar el comportamiento de cambio de tamaño.

Quote:

A menos que se especifique al menos un valor distinto de cero para weightx o pesada, todos los componentes se agrupan en el centro de su contenedor. Esto se debe a que cuando el peso es 0.0 (valor predeterminado), GridBagLayout pone cualquier espacio adicional entre su cuadrícula de celdas y los bordes del contenedor.

Lo siguiente mantendrá a myComponent en la esquina NORTHWEST. Suponiendo this es JPanel o similar:

setLayout(new GridBagLayout()); 
GridBagConstraints c = new GridBagConstraints(); 

// Specify horizontal fill, with top-left corner anchoring 
c.fill = GridBagConstraints.HORIZONTAL; 
c.anchor = GridBagConstraints.NORTHWEST; 

// Select x- and y-direction weight. Without a non-zero weight, 
// the component will still be centered in the given direction. 
c.weightx = 1; 
c.weighty = 1; 

// Add child component 
add(myComponent, c); 

para mantener los componentes hijo izquierdo-alineados todavía verticalmente centrada, acaba de establecer anchor = WEST y quitar weighty = 1;.

0

Puede establecer el diseño principal como diseño de flujo y establecer la alineación como izquierda. en este panel (diagrama de flujo), agregue un panel que sea gridbaglayout. también esto se trabaja en netbeans

0

Otra solución es que añades dos paneles falsos (contenedor) a la derecha, la parte más inferior. luego ajusta weightx y weighty para distribuir espacio extra. si establece 1 en el maniquí, todo el espacio adicional se asigna a este maniquí.

este es un ejemplo que se forma en netbeans.

package tutorial; 

/** 
* 
* @author ttn 
*/ 
public class GridBag1 extends javax.swing.JPanel { 

    /** 
    * Creates new form GridBag1 
    */ 
    public GridBag1() { 
     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() { 
     java.awt.GridBagConstraints gridBagConstraints; 

     jLabel1 = new javax.swing.JLabel(); 
     jTextField1 = new javax.swing.JTextField(); 
     jPanel1 = new javax.swing.JPanel(); 
     jPanel2 = new javax.swing.JPanel(); 
     jLabel2 = new javax.swing.JLabel(); 
     jTextField2 = new javax.swing.JTextField(); 
     jScrollPane1 = new javax.swing.JScrollPane(); 
     jTextArea1 = new javax.swing.JTextArea(); 

     setLayout(new java.awt.GridBagLayout()); 

     jLabel1.setText("jLabel1"); 
     gridBagConstraints = new java.awt.GridBagConstraints(); 
     gridBagConstraints.gridx = 0; 
     gridBagConstraints.gridy = 0; 
     add(jLabel1, gridBagConstraints); 

     jTextField1.setText("jTextField1"); 
     jTextField1.setMinimumSize(new java.awt.Dimension(59, 20)); 
     gridBagConstraints = new java.awt.GridBagConstraints(); 
     gridBagConstraints.gridx = 1; 
     gridBagConstraints.gridy = 0; 
     gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; 
     gridBagConstraints.weightx = 0.3; 
     add(jTextField1, gridBagConstraints); 

     javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); 
     jPanel1.setLayout(jPanel1Layout); 
     jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGap(0, 227, Short.MAX_VALUE) 
     ); 
     jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGap(0, 104, Short.MAX_VALUE) 
     ); 

     gridBagConstraints = new java.awt.GridBagConstraints(); 
     gridBagConstraints.gridx = 2; 
     gridBagConstraints.gridy = 0; 
     gridBagConstraints.gridheight = 3; 
     gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; 
     gridBagConstraints.weightx = 1.0; 
     add(jPanel1, gridBagConstraints); 

     javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); 
     jPanel2.setLayout(jPanel2Layout); 
     jPanel2Layout.setHorizontalGroup(
      jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGap(0, 172, Short.MAX_VALUE) 
     ); 
     jPanel2Layout.setVerticalGroup(
      jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGap(0, 196, Short.MAX_VALUE) 
     ); 

     gridBagConstraints = new java.awt.GridBagConstraints(); 
     gridBagConstraints.gridx = 0; 
     gridBagConstraints.gridy = 3; 
     gridBagConstraints.gridwidth = 2; 
     gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; 
     gridBagConstraints.weighty = 1.0; 
     add(jPanel2, gridBagConstraints); 

     jLabel2.setText("jLabel2"); 
     gridBagConstraints = new java.awt.GridBagConstraints(); 
     gridBagConstraints.gridx = 0; 
     gridBagConstraints.gridy = 1; 
     add(jLabel2, gridBagConstraints); 

     jTextField2.setText("jTextField2"); 
     jTextField2.setMinimumSize(new java.awt.Dimension(59, 20)); 
     gridBagConstraints = new java.awt.GridBagConstraints(); 
     gridBagConstraints.gridx = 1; 
     gridBagConstraints.gridy = 1; 
     gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; 
     gridBagConstraints.weightx = 0.3; 
     add(jTextField2, gridBagConstraints); 

     jScrollPane1.setMinimumSize(new java.awt.Dimension(104, 64)); 

     jTextArea1.setColumns(20); 
     jTextArea1.setRows(5); 
     jScrollPane1.setViewportView(jTextArea1); 

     gridBagConstraints = new java.awt.GridBagConstraints(); 
     gridBagConstraints.gridx = 0; 
     gridBagConstraints.gridy = 2; 
     gridBagConstraints.gridwidth = 2; 
     gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; 
     add(jScrollPane1, gridBagConstraints); 
    }// </editor-fold>       


    // Variables declaration - do not modify      
    private javax.swing.JLabel jLabel1; 
    private javax.swing.JLabel jLabel2; 
    private javax.swing.JPanel jPanel1; 
    private javax.swing.JPanel jPanel2; 
    private javax.swing.JScrollPane jScrollPane1; 
    private javax.swing.JTextArea jTextArea1; 
    private javax.swing.JTextField jTextField1; 
    private javax.swing.JTextField jTextField2; 
    // End of variables declaration     
} 
Cuestiones relacionadas