JButton expandindo -se para pegar o quadro/contêiner inteiro
-
10-07-2019 - |
Pergunta
Ei pessoal. Estou tentando fazer uma GUI de balanço com um botão e um rótulo. Estou usando um layout de borda e o rótulo (no campo norte) aparece bem, mas o botão pega o restante do quadro (está no campo central). Alguma ideia de como consertar isso?
Solução
Você deve adicionar o botão a outro painel e, em seguida, adicionar esse painel ao quadro.
Acontece que o BorderLayout expande o que quer que seja o componente no meio
Seu código deve ficar assim agora:
Antes da
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 );
....
}
Mude para algo assim:
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 Depois
Antes de http://img372.imageshack.us/img372/2860/befordl1.png Depois de http://img508.imageshack.us/img508/341/aftergq7.png
Outras dicas
Ou apenas use layout absoluto. Está no palete dos layouts.
Ou habilitá -lo com:
frame = new JFrame();
... //your code here
// to set absolute layout.
frame.getContentPane().setLayout(null);
Dessa forma, você pode colocar livremente o controle em qualquer lugar que desejar.
Novamente :)
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);
}
}