Pregunta

Hola a todos. Estoy tratando de hacer una interfaz gráfica de usuario con un botón y una etiqueta. estoy usando un diseño de borde y la etiqueta (en el campo norte) aparece bien, pero el botón ocupa el resto del marco (está en el campo central). alguna idea de cómo solucionar esto?

¿Fue útil?

Solución

Debe agregar el botón a otro panel y luego agregar ese panel al marco.

Resulta que BorderLayout expande cualquier componente que esté en el medio

Su código debería verse así ahora:

Antes

public static void main( String [] args ) {
    JLabel label = new JLabel("Some info");
    JButton button = new JButton("Ok");

    JFrame frame = ... 

    frame.add( label, BorderLayout.NORTH );
    frame.add( button , BorderLayout.CENTER );
    ....

}

Cámbielo a algo como esto:

public static void main( String [] args ) {
    JLabel label = new JLabel("Some info");
    JButton button = new JButton("Ok");
    JPanel panel = new JPanel();
     panel.add( button );

    JFrame frame = ... 

    frame.add( label, BorderLayout.NORTH );
    frame.add( panel , BorderLayout.CENTER);
    ....

}

Antes / Después

Antes http://img372.imageshack.us/img372/2860/beforedl1.png Después de http://img508.imageshack.us/img508/341/aftergq7.png

Otros consejos

O simplemente use el diseño absoluto. Está en la paleta de diseños.

O habilítelo con:

frame = new JFrame();
... //your code here

// to set absolute layout.
frame.getContentPane().setLayout(null);

De esta manera, puede colocar libremente el control en cualquier lugar que desee.

Otra vez :)


    import javax.swing.*;

    public class TestFrame extends JFrame {
        public TestFrame() {
            JLabel label = new JLabel("Some info");
            JButton button = new JButton("Ok");
            Box b = new Box(BoxLayout.Y_AXIS);
            b.add(label);
            b.add(button);
            getContentPane().add(b);

        }
        public static void main(String[] args) {
            JFrame f = new TestFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setLocationRelativeTo(null);
            f.setVisible(true);

        }
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top