Centralizar button no final do frame

4 respostas
DANIEL35
Olá pessoal, estou desenvolvendo uma tela de cadastros e não estou conseguindo centralizar os botões no fim do frame, ou seja, separá-los dos outros campos. Alguém poderia me auxiliar nesse problema? Obrigado. Vejam o código:
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;     
import javax.swing.text.MaskFormatter;   
import java.text.ParseException;  
import java.awt.Color;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.*;

public class CadastroAluno extends JFrame{
    private JButton b1, b2, b3, b4;
    private JLabel l0, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13;
    private JTextField c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12;
    private TratarBotoesTelaAluno tba;
    private JComboBox combo, combo_2;
    private static final long serialVersionUID = 1L;  
    private JFormattedTextField data, telefone, telefone_cel, cpf, cep; 
    private MaskFormatter Dat, Tel, Tel_cel, CPF, CEP;
		
	public CadastroAluno() {
		setTitle("CADASTRO DE ALUNOS");			
	    JPanel p1 = new JPanel();     
        p1.setLayout(new FlowLayout(FlowLayout.LEFT));       
		JPanel p2 = new JPanel();    
		p2.setLayout(new FlowLayout());  
        
        Icon bug = new ImageIcon("travelbug.gif");   
    	JLabel l0 = new JLabel(new ImageIcon("C:\PPI\CADASTRO.jpg"));
    	p1.add(l0); 
    	
    	try {  
            Tel = new MaskFormatter("##-####-####");  
        } catch (ParseException e) {  
            e.printStackTrace();  
        } 
        try {  
            Tel_cel = new MaskFormatter("##-####-####");  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }         
        try {  
            Dat = new MaskFormatter("##/##/####");  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }  
        try {  
           CPF = new MaskFormatter("###-###-###-##");  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }
          try {  
           CEP = new MaskFormatter("#####-###");  
        } catch (ParseException e) {  
            e.printStackTrace();  
        }                    
        telefone = new JFormattedTextField(Tel);  
        telefone_cel = new JFormattedTextField(Tel_cel); 
        cpf = new JFormattedTextField(CPF);
        data = new JFormattedTextField(Dat);
        cep = new JFormattedTextField(CEP);     
        Tel.setValidCharacters("[telefone removido]");
        Tel_cel.setValidCharacters("[telefone removido]"); 
        CPF.setValidCharacters("[telefone removido]");         
        Dat.setValidCharacters("[telefone removido]");
        CEP.setValidCharacters("[telefone removido]"); 
            
        telefone.setColumns(9);
        telefone_cel.setColumns(9);
        cpf.setColumns(10);  
        data.setColumns(7);
        cep.setColumns(9);           
        
        String sexo[] = {"M","F"};
    	combo = new JComboBox(sexo);
   	 	combo.setBackground(Color.white);
    	combo.setForeground(Color.black);
    	combo.addItemListener(new ItemListener(){
      	public void itemStateChanged(ItemEvent ie){
        String str = (String)combo.getSelectedItem();
      }
    });
    
    	String uf[] = {"AC","AL","AP","AM","BA","CE","DF","ES","GO","MA","MT","MS","MG","PA","PB","PR","PE","PI","RR","RO","RJ","RN","RS","SC","SP","SE","TO"};
    	combo_2 = new JComboBox(uf);
   	 	combo_2.setBackground(Color.white);
    	combo_2.setForeground(Color.black);
    	combo_2.addItemListener(new ItemListener(){
      	public void itemStateChanged(ItemEvent ie){
        String str = (String)combo_2.getSelectedItem();
      }
    });
    	b1 = new JButton("Novo");
    	b2 = new JButton("Salvar");
    	b3 = new JButton("Limpar");  
    	b4 = new JButton("Deletar");  
    	   	  	
        l1 = new JLabel ("Matrícula nº:");
    	l2 = new JLabel ("Nome:");
    	l3 = new JLabel ("CPF:");
  		l4 = new JLabel ("Sexo:");
    	l5 = new JLabel ("Nascimento");
    	l6 = new JLabel ("tel residencial:");
    	l7 = new JLabel ("tel celular:");
    	l8 = new JLabel ("Endereço:");
    	l9 = new JLabel ("nº");
    	l10 = new JLabel ("Bairro:");
    	l11 = new JLabel("Cidade:");
    	l12 = new JLabel("Estado:");
    	l13 = new JLabel ("CEP:");
    	c1 = new JTextField (5);
    	c2 = new JTextField (36);
    	c3 = new JTextField (15);
    	c5 = new JTextField (10);
    	c6 = new JTextField (10); 
    	c7 = new JTextField (30);
    	c8 = new JTextField (31);
    	c9 = new JTextField (7);
    	c10 = new JTextField (17);   	
    	c11	= new JTextField (17); 
    	c12 = new JTextField (10); 
    	
    	JTextField [] vetTF = { c1, c2, c3, c5, c6, c7, c8, c9, c10, c11, c12, cpf, data, telefone, telefone_cel, cep};
    	
    	p1.add(l1);
    	p1.add(c1);
    	p1.add(l2);
    	p1.add(c2);
    	p1.add(l3);
    	p1.add(cpf);    	
    	p1.add(l4);
    	p1.add(combo);
    	p1.add(l5);
    	p1.add(data);
    	p1.add(l6);
    	p1.add(telefone);
    	p1.add(l7);
    	p1.add(telefone_cel);
    	p1.add(l8);
    	p1.add(c8);
    	p1.add(l9); 
    	p1.add(c9);   
    	p1.add(l10);
    	p1.add(c10);
    	p1.add(l11);
    	p1.add(c11);    	
    	p1.add(l12);
    	p1.add(combo_2);
    	p1.add(l13);
    	p1.add(cep);    
    	p1.add(p2);
       	
    	p2.add(BorderLayout.SOUTH,b1);  // colocar os botões no rodapé do frame!!...  
    	p2.add(BorderLayout.SOUTH,b2);  
    	p2.add(BorderLayout.SOUTH,b3);
    	p2.add(BorderLayout.SOUTH,b4);
    	    	
    	b1.setForeground(Color.blue);
    	b2.setForeground(Color.blue);
    	b3.setForeground(Color.blue);
    	b4.setForeground(Color.red);    	
    	tba = new TratarBotoesTelaAluno(b1,b2,b3,b4, vetTF); 
    	b1.addActionListener(tba);
		b2.addActionListener(tba);
		b3.addActionListener(tba); 
		b4.addActionListener(tba);
		this.setContentPane(p1); 
		setSize(600,350);
		setResizable(false);
		setLocationRelativeTo(null);
	}
}

4 Respostas

T

Tio, não consegui entender como é que você quer arrumar os JTextFields e os botões. Experimente usar o MiGLayout ( http://www.miglayout.com/ ) e seja feliz!

(Se quiser, em vez disso, pedir a Deus que o mate e ao diabo que o carregue, experimente usar o GridBagLayout - altamente recomendado, pelo menos po quem fez esta animação Flash: http://madbean.com/anim/totallygridbag/ )

DANIEL35

Eae “TIO”, será que não consegui ser claro??! O que estou precisando é apenas colocar os 4 botões que criei, na parte sul do frame. Tipo BorderLayout.SOUTH.. Entendeu agora?

T

Acho mais fácil ver um desenho - sou meio cego para essas coisas.

Mas em geral, se você não for usar o MigLayout, você não deve economizar em criar JPanels que servem apenas para distribuir grupos de componentes. Por exemplo, se quiser ter um grupo de 3 botões centralizados na parte de baixo de um diálogo (por exemplo), crie um JPanel que serve para pôr esses botões, use o layout FlowLayout (como você fez) para esse JPanel, ponha os botões dentro desse JPanel, e então ponha o tal JPanel em algum lugar (por exemplo, na parte SOUTH de algum outro JPanel com BorderLayout, por exemplo).
Se for usar o MigLayout, toda essa festa de ficar criando montes e montes de JPanels só para organizar componentes do jeito que você quer acaba - é só descrever os “constraints” de acordo com o MigLayout e você aproveita o seu tempo para coisas mais úteis.

DANIEL35

Valeu, vou testar e depois posto o resultado.

Criado 4 de junho de 2010
Ultima resposta 4 de jun. de 2010
Respostas 4
Participantes 2