Swing Gridbaglayout - automatische Anpassung verhindern

Neumi5694

Top Contributor
Gridbaglayout ist mein absoluter Favorit. Nur wäre es manchmal ganz hilfreich, wenn die Größe eines Elements auch bei Änderung des Inhalts sich nicht mehr ändert, dass z.B. der angezeigte Text eines Labels oder Textfelds sich nicht auf die Breite des Feldes auswirkt. Die Breite soll einzig und allein von den GridbagConstraints abhängen. Ist das machbar?

Z.B. muss ich manchmal einen Wert in ein Label schreiben, manchmal nicht. Steht der Wert drin, ändert sich das gesamte umgebende Layout, das möchte ich verhindern. Es besteht mehr als genug Platz für jeden möglichen anzuzeigenden Text.
 
gib doch dem label eine feste breite und diese wird dann im gb übernommen, hab hier mal eine beispiel mit einem textfield

Java:
private static final int TF_SIZE =15;
JTextField nameTF =new JTextField( TF_SIZE);

public initLayout(){
        gbc.insets =new Insets(5, 5, 2, 5);
        //            x, y, w, h,  wx,   wy, fill                       gbc, panel, Component
        addComponent( 0, 0, 1, 1,    0,    0, GridBagConstraints.EAST,  gbc, panel, nameL);
        addComponent( 1, 0, 1, 1,  0.5,    0, GridBagConstraints.WEST,  gbc, panel, nameTF);
    }
    
    /**
     * Interne Methode zum hinzufügen der einzeln Componenten auf das Panel
     * 
     * @param gridx Colum
     * @param gridy Row
     * @param width count of Colums
     * @param height count of Rows
     * @param weightx percent of the colum for the Component
     * @param weighty percent of the row for the Component
     * @param fill fill orientation
     * @param gbc GridBagConstraints
     * @param pnl 
     * @param c Component to add
     */
    private void addComponent( int gridx, int gridy, int width, int height, double weightx, double weighty, int fill,
                               GridBagConstraints gbc, JPanel pnl, Component c){
        gbc.gridx      =gridx;    gbc.gridy     =gridy;
        gbc.weightx    =weightx;  gbc.weighty   =weighty;
        gbc.gridheight =height;   gbc.gridwidth =width;
        gbc.fill =fill;
        pnl.add( c, gbc);
    }
 

Zurück
Oben