Como montar um Formulário em java
Autor: welton silva | Publicado: 2013-08-17T20:21:00-03:00

Ae Galera....

Hoje vou passar um exemplo bem fácil de como montar seus formulário.

&nbsp;Segue o código


package vision;

import java.awt.Dimension;

import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

//Será uma classe que será um formulário
public class Form extends JFrame {

&nbsp;&nbsp;&nbsp; /**
&nbsp;&nbsp;&nbsp; &nbsp;* 
&nbsp;&nbsp;&nbsp; &nbsp;*/
&nbsp;&nbsp;&nbsp; private static final long serialVersionUID = 1L;


&nbsp;&nbsp;&nbsp; // Declarando os componentes no formulário.

&nbsp;&nbsp;&nbsp; // Títulos dos campos
&nbsp;&nbsp;&nbsp; //vou usar (for) para preencher os nomes e posições dos campos no formulários
&nbsp;&nbsp;&nbsp; String[] tituloCampos = { "Código", "Nome", "Sobrenome" };

&nbsp;&nbsp;&nbsp; // Tamanho dos campos
&nbsp;&nbsp;&nbsp; int[] tamanhoCampos = { 5, 30, 30 };

&nbsp;&nbsp;&nbsp; // Declarado um array de campos e descrição de campos
&nbsp;&nbsp;&nbsp; JTextField[] txtCampos;
&nbsp;&nbsp;&nbsp; JLabel[] lblCampos;

&nbsp;&nbsp;&nbsp; // Criado um Painel para deixar os botões
&nbsp;&nbsp;&nbsp; JPanel jpBotoes;

&nbsp;&nbsp;&nbsp; // Desclarado os botões.
&nbsp;&nbsp;&nbsp; JButton btnInserir;
&nbsp;&nbsp;&nbsp; JButton btnAlterar;
&nbsp;&nbsp;&nbsp; JButton btnPesquisar;
&nbsp;&nbsp;&nbsp; JButton btnExcluir;
&nbsp;&nbsp;&nbsp; JButton btnFechar;

&nbsp;&nbsp;&nbsp; // Método construtor que será iniciado ao instânciar a classe
&nbsp;&nbsp;&nbsp; public Form() {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // Iniciado o método que montará o formulário
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; initForm();
&nbsp;&nbsp;&nbsp; }

&nbsp;&nbsp;&nbsp; // Método que montará o formulário
&nbsp;&nbsp;&nbsp; private void initForm() {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // Será setado o layout GridBagLayout que vc poderá montrar os componentes
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // imaginando ser uma planilha excel.
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.setLayout(new GridBagLayout());

&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // Instânciamos o GridBagConstrants que será onde setaremos a formatação
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // dos componentes para inserir no
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // Layout do Formulário
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; GridBagConstraints gbc = new GridBagConstraints();

&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // dizemos como ficará o texto dentro do componente inserido
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; gbc.anchor = GridBagConstraints.WEST; //a esquerda vai ficar
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // Dizemos qual será o espaçamento dos componentes com relação aos outros
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // componentes
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; gbc.insets = new Insets(10, 10, 10, 10); //espaçamento

&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // Dizemos em qual coluna irá iniciar a inserção dos componentes
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; gbc.gridx = 0;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; gbc.gridy = 0;
&nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // Instânciamos os array de label e textfield com a quantidade de campos a ser inserida
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // Insta baseado na quantidade de titulos na variavel global
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; lblCampos = new JLabel[tituloCampos.length];
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; txtCampos = new JTextField[tituloCampos.length];

&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // Entra no for para colocar a formatação dos campos um por um,
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // seguindo a ordem das linhas
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; for (int i = 0; tituloCampos.length &gt; i; i++) {
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Instanciando a label i do array
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; lblCampos[i] = new JLabel();
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Settando o nome do campo
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; lblCampos[i].setText(tituloCampos[i]);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Adiciona no formulario com a formatação dentro do GridBagLayout Instanciado
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.add(lblCampos[i], gbc);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Coloca para adicionar o próximo componente dentro da proxima coluna
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; gbc.gridx += 1;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Instância o campo na posição i do array
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; txtCampos[i] = new JTextField();
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Informa o tamanho do campo baseado na array com os tamanhos.
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Somente multipliquei por 10 para ficar com um tamanho bom, não é padrão esse cálculo
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; txtCampos[i].setPreferredSize(new Dimension(tamanhoCampos[i] * 10,
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 20));
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Adicionando no formulário
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.add(txtCampos[i], gbc);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Coloca na proxima linha os outros componentes
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; gbc.gridy += 1;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Volta para a coluna 0
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; gbc.gridx = 0;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Fim do for
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Instânciando o painel onde ficará os botões
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; jpBotoes = new JPanel();
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Dizemos qual será seu tamanho.
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; jpBotoes.setPreferredSize(new Dimension(500, 40));
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Colocamos no layout FlowLayout que coloca os componentes como se fossem palavras num editor. ex 1 2 3 4 5. em linha
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; jpBotoes.setLayout(new FlowLayout());

&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Instanciando o botão inserir e já colocando o nome
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; btnInserir = new JButton("Inserir");
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Adcionando ao painel onde ficará os botoes
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; jpBotoes.add(btnInserir);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Fazemos como acima nos demais botões. Instanciamos, colocamos nome e adicionamos ao painel 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; btnAlterar = new JButton("Alterar");
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; jpBotoes.add(btnAlterar);

&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; btnExcluir = new JButton("Excluir");
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; jpBotoes.add(btnExcluir);

&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; btnPesquisar = new JButton("Pesquisar");
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; jpBotoes.add(btnPesquisar);

&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; btnFechar = new JButton("Fechar");
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; jpBotoes.add(btnFechar);

&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; // Dizemos em qual coluna e linha vai ficar o painel
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; gbc.gridx = 0;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; gbc.gridy = gbc.gridy + 1;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Essa opção é como a função mesclar do excel, permite fazer o componente ocupar quantas colunas settar
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; gbc.gridwidth = 5;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Iniciamos o painel. e deixamos visivel
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; jpBotoes.setVisible(true);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Adicionamos ao formulário o painel com a formatação
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.add(jpBotoes, gbc);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Dizemos que vai ficar com o tamanho proporcional ao tanto de componentes inseridos o formulário
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.pack();
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Colocamos para inserir centralizado na tela
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.setLocationRelativeTo(null);
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Setamos o titulo do formulário
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.setTitle("Cadastro de pessoas");
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; 
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; //Setamos o funcionamento do botão fechar no formulário
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; //Fim do metodo que inicia o formulário
}
//fim