Pregunta

Solo estoy tratando de agregar 3 botones verticales centrados a un GridbagLayout en Java Swing. En este momento creo que el tamaño predeterminado de la cuadrícula es 3x3. Quería saber si puedo cambiar eso y agregar más columnas y filas. Simplemente quiero hacer 3 butons igualmente espaciados centrados en un panel.

    pane.setLayout(new GridLayout(10,1));
    // Insert a space before the first button
    for (int i = 1; i < 6; i++ ){
        pane.add(new JLabel(""));
    }
    pane.add(new Button("1"));
    pane.add(new Button("2"));
        pane.add(new Button("3"));
    // Insert a space after the last button
    pane.add(new JLabel(""));

Esa fue la solución final gracias a todos!

¿Fue útil?

Solución

Estoy de acuerdo con @Chris A GridLayout sería más fácil:

myPanel.setLayout(new GridLayout(5,1));
// Insert a space before the first button
add(new JLabel(""));
add(new Button("1"));
add(new Button("2"));
add(new Button("3"));
// Insert a space after the last button
add(new JLabel(""));

Otros consejos

Simplemente agregue más valores a los atributos de pesas. Esto le dice cómo colocar la bolsa de cuadrícula - 0 significa usar solo el espacio necesario, entonces el resto del espacio se divide de acuerdo con los pesos dados.

GridBagLayout gbl = new GridBagLayout();
...
gbl.columnWeights = new double[] {1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
gbl.rowWeights = new double[] {1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
...
contentPane.setLayout(gbl_contentPane);

Y luego da tus artículos GridBagConstraints con gridx y gridy Establezca apropiadamente (de 0) para las nuevas columnas/filas:

GridBagConstraints gbc = new GridBagConstraints();
...
gbc.gridx = 3;
gbc.gridy = 3;
...
contentPane.add(textFieldName, gbc_textFieldName);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top