Escolar Documentos
Profissional Documentos
Cultura Documentos
Progração Java Com Projeto de Banco de Dados - Apostila PDF
Progração Java Com Projeto de Banco de Dados - Apostila PDF
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
18 – Maiúsculas e Minúsculas
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
28 – O que SQL?
28.1 – Como usar SQL?
28.2 – Tipos de Dados
29 – ODBC/JDBC
29.1 – O que é um Driver?
29.2 – O que é ODBC?
29.3 – O que é JDBC?
29.4 – JDBC / ODBC
29.5 – DriverManager
29.6 – Como Criar Fontes de Dados ODBC
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
1 – Introdução
É o fato de ter sido projetada levando em conta o que havia de melhor e pior
nos cinqüenta anos de existências das linguagens de programação. Java parte
do que deu ou não certo nas linguagens que a precederam ou lhe foram
contemporâneas. E suas características fazem-na uma linguagem muito útil
nestes tempos de interconectividade e migração tecnológica constantes.
A origem do nome Java por si só é material para um livro inteiro. Existem muita
especulação e lenda associada aos motivos que levaram os criadores da
linguagem Java – inicialmente chamada OAK, a batizaram-na como este nome
e a associaram ao café.
O mais importante é você saber que inicialmente a linguagem Java não incluía
a internet em suas pretensões. Hoje tem se mostrado a linguagem ideal para
desenvolvimento para internet e computação distribuída. Também está voltada
às origens, ao ser cogitada pelas grandes indústrias como linguagem de
programação para eletroeletrônicos e eletrodomésticos.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Interpretador
Java
Código Fonte Compilador Binário Java (runtime Java ou
Arquivo.java Java Arquivo.class JVM – Java
Virtual
Machine/Máquina
Virtual Java)
O compilador Java gera JVM para WIN32
um arquivo binário com o
O código fonte é mesmo nome do arquivo
um arquivo gravado com a extensão.
digitado em Compilador Java. Esse arquivo é o
qualquer editor de Javac programa em Java e JVM para
texto puro e salvo pode ser executado em SOLARIS
com extensão qualquer máquina que
.Java possua a Java Virtual
Machine instalada. É
como se tivéssemos um
computador dentro do JVM para Linux
outro (emulador).
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Creio que você não terá problemas para atingir os mesmos resultados.
Optamos pelo JCreator por ele ser gratuito, pequeno, fácil de usar, estável e
cumpre o que promete: edita o código-fonte, compila, executa e ajuda a
depurar erros. Outras duas características muito úteis são endentações
automáticas e o uso de cores para diferentes partes do código-fonte.
Na mesma página em que você encontra a versão gratuita está a versão Pro
que é paga e só funciona por 30 dias. Tenha certeza de estar baixando a
versão LE que é gratuita e atende perfeitamente aos nossos objetivos.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Clique em Next para avançar, aceitando o JCreator como editor associado aos
arquivos Java. Como já foi visto, os arquivos com a extensão Java nada mais
são do que arquivos texto contendo o código-fonte escrito em linguagem Java.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
JCreator. Da próxima vez que for executado, estes procedimentos não serão
mais executados.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
public class teste extends JFrame{
public teste(){
super("Testando o JCreator");
setSize(300, 150);
setVisible(true);
}
public static void main(String args[]){
teste app = new teste();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Se tudo correu bem, será exibida na parte inferior do JCreator uma janela com
a mensagem Process Completed. O processamento não é imediato. Aguarde
até que alguma mensagem apareça ou o seu bom senso o alerte para algum
problema.
Nota: toda vez que você fizer alguma alteração no código-fonte terá de
compilar o código-fonte de novo, para que as mudanças reflitam na classe.
Mas se tudo correu bem durante a compilação do teste.Java, agora você tem
uma classe pronta para se interpretada pela Máquina Virtual Java, Basta clicar
no botão execute File do JCreator.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Esta classe que compilamos e executamos foi uma forma fácil e rápida de
testar o ambiente e também de prepará-lo para os capítulos seguintes da
apostila. A única coisa que ela faz é exibir uma janela com a frase na barra
“Testando o Uso do JCreator”. Feche a janela e depois pressione qualquer
tecla para fechar do console e retornar ao JCreator.
Lembre-se que todos os exercícios e tarefas deste apostila são digitadas,
compiladas e executadas de dentro do JCreator. Se você teve alguma
dificuldade nos passos anteriores, repita-os até está seguro do processo:
Digitar -> Compilar-> Executar -> Depurar quando se fizer necessário, pois
são tarefas fundamentais para a compreensão e prática dos próximos
capítulos.
Início
Digitação do Código
.Java
Compilar
.class
Problemas na Depuração
compilação?
sim
não
Executar
.class
Fim
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A numeração das linhas não faz parte do programa. Ela serve para ajudar na
identificação de cada linha, as quais vamos analisar a partir de agora.
3.3 – Comentários
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Inteiros:
Tipo Tamanho
byte 1 byte
short 2 bytes
Int 4 bytes
long 8 bytes
Ponto Flutuante:
Tipo Tamanho
float 8 byte
double 8 bytes
Caractere:
Tipo Tamanho
char 2 bytes
Booleano:
Tipo Tamanho
boolean 1 byte
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
int val1;
float val2;
double val3;
val1 = Integer.parseInt(valor1);
val2 = Float.parseFloat(valor2);
val3 = Double.parseDouble(valor3);
Conversão implícita:
Conversão explícita
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
3.7 – Operadores
Operadores
Operador Nome Exemplo de uso
+ Adição A+B
- Subtração A-B
/ Divisão A/B
* Multiplicação A*B
% Módulo A%B
- Negativo (unário) A =-A
++ Incremento A++
++A
-- Decremento A—
--A
Operadores Bitwise
Operador Nome Exemplo de uso
~ Inversão ~A
& E (and) A&B
| OU (OR) A|B
^ XOU (XOR) A ^B
<< Deslocamento à esquerda A << B
>> Deslocamento à direita A >> B
= atribuição A=B
3.8 – Variáveis
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Frame
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Frame JFrame
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Uma classe JFrame pode ser instanciada de duas maneiras: app = new()
que cria uma instância da classe que é inicialmente invisível, mas sem um título
na barra de títulos, ou: app = new(String Título)
que cria uma instância da classe inicialmente invisível e com um objeto String
representando o texto da barra de títulos. Assim, no construtor da classe
PrimeiraJanela, invocamos o segundo construtor da superclasse JFrame
fornecendo o texto que queremos como título da janela.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
public class TamanhoFixo extends JFrame{
public TamanhoFixo(){
super("Uma janela não dimensionável");
setResizable(false);
setSize(300, 150);
setVisible(true);
}
public static void main(String args[]){
TamanhoFixo app = new TamanhoFixo();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
public class JanelaCentralizada extends JFrame{
public JanelaCentralizada (){
super("Janela Centralizada");
setSize(300, 150);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
JanelaCentralizada app = new JanelaCentralizada ();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Temos que importar o pacote import java.awt.*;, pois a classe Container está
nele. Veja como uma instância dessa classe é criada e atribuída à referência
tela: Container tela = getContentPane();
Você sabia que você pode editar cores personalizadas para suas janelas de
aplicativos Java? Com o comando setBackground (), isso é possível.
Veja o exemplo:
import javax.swing.*;
import java.awt.*;
public class CorDeFundo2 extends JFrame{
public CorDeFundo2(){
super("Definindo a cor de fundo para a janela");
Container tela = getContentPane();
tela.setBackground(new Color(255,128,128));
setSize(500, 100);
setVisible(true);
}
public static void main(String args[]){
CorDeFundo2 app = new CorDeFundo2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
tela.setBackground(new Color(255,128,128));
tela.setBackground(new Color(255,228,228));
tela.setBackground(new Color(255,255,204));
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Após executar o aplicativo, observe como o ícone padrão (a xícara de café) foi
alterada, substituída pela imagem que foi adicionada no aplicativo.
A definição de um ícone para a janela pode ser realizada com apenas duas
linhas de código: ImageIcon icone = new ImageIcon("teste.gif");
setIconImage(icone.getImage());
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
public class ExemploLabel extends JFrame{
JLabel rotulo1,rotulo2,rotulo3,rotulo4;
public ExemploLabel(){
super("Exemplo com Label");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel ("Nome");
rotulo2 = new JLabel ("Idade");
rotulo3 = new JLabel ("Telefone");
rotulo4 = new JLabel ("Celular");
rotulo1.setBounds(50,20,80,20);
rotulo2.setBounds(50,60,80,20);
rotulo3.setBounds(50,100,80,20);
rotulo4.setBounds(50,140,80,20);
rotulo1.setForeground(Color.red);
rotulo2.setForeground(Color.blue);
rotulo3.setForeground(new Color(190,152,142));
rotulo4.setForeground(new Color(201,200,100));
rotulo1.setFont(new Font("Arial",Font.BOLD,14));
rotulo2.setFont(new Font("Comic Sans MS",Font.BOLD,16));
rotulo3.setFont(new Font("Courier New",Font.BOLD,18));
rotulo4.setFont(new Font("Times New Roman",Font.BOLD,20));
tela.add(rotulo1);
tela.add(rotulo2);
tela.add(rotulo3);
tela.add(rotulo4);
setSize(400, 250);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploLabel app = new ExemploLabel();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
5.3 - Próximo passo definir o largura e altura do JLabel e a coluna e a linha que
ele irá ocupar na janela.
rotulo1.setBounds(50,20,80,20);
rotulo2.setBounds(50,60,80,20);
rotulo3.setBounds(50,100,80,20);
rotulo4.setBounds(50,140,80,20);
Comprimento 80
Linha 20
Linha 60
Coluna 50
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
5.4 - Próximo passo definir a cor da letra dos componentes JLabel, lembrando
que se esses objetos não forem adicionados ao aplicativo, a cor default é preto.
rotulo1.setForeground(Color.red);
rotulo2.setForeground(Color.blue);
5.5 - Esses dois trechos abaixo especifica como criar cores personalizadas
para o componente JLabel.
rotulo3.setForeground(new Color(190,152,142));
rotulo4.setForeground(new Color(201,200,100));
rotulo1.setFont(new Font("Arial",Font.BOLD,14));
rotulo2.setFont(new Font("Comic Sans MS",Font.BOLD,16));
rotulo3.setFont(new Font("Courier New",Font.BOLD,18));
rotulo4.setFont(new Font("Times New Roman",Font.BOLD,20));
Lembrando que o nome da fonte tem que ser definida como esta na opção de
fonte do sistema.
rotulo1.setFont(new Font("Arial",Font.BOLD,14));
Você pode definer 14, 16, 18, 20 entre outros tamanhos que fica a escolha do
usuário.
E finalmente o método tela que representa a janela deverá ser chamado, onde
vai exibir o rótulo o conteúdo do JLabel na janela.
tela.add(rotulo1);
tela.add(rotulo2);
tela.add(rotulo3);
tela.add(rotulo4);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
public class LabelImagem extends JFrame{
JLabel imagem;
public LabelImagem(){
super("Uso da classe JLabel com Imagem");
Container tela = getContentPane();
ImageIcon icone = new ImageIcon("sapo.jpeg");
imagem = new JLabel(icone);
tela.add(imagem);
setSize(500, 460);
setVisible(true);
}
public static void main(String args[]){
LabelImagem app = new LabelImagem();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 3 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 3 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
7.3 - Botão somente com imagem: Exemplo de botão somente com figura:
import java.awt.event.*;
public class ExemploBotao extends JFrame{
JButton botao;
ImageIcon icone;
public ExemploBotao(){
super("Exemplo com JButton");
Container tela = getContentPane();
setLayout(null);
icone = new ImageIcon("abrir.gif");
botao = new JButton (icone);
botao.setBounds(50,20,100,20);
tela.add(botao);
setSize(400, 250);
setVisible(true);
setLocationRelativeTo(null);
}
Muito simples fazer esse tipo de botão com o aplicativo anterior de botão com
imagem basta você retirar o texto de dentro da linha que somente a imagem
será adicionada, veja a linha:
Linha do botão com texto e imagem: botão = new JButton (“Abrir”,icone);
Linha do botão somente com imagem: botão = new JButton (icone);
Aplicativo com os três botões
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 3 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
botao1.setBounds(50,20,100,20);
botao2.setBounds(50,60,100,20);
botao3.setBounds(50,100,100,20);
botao4.setBounds(50,140,100,20);
tela.add(botao1);
tela.add(botao2);
tela.add(botao3);
tela.add(botao4);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploBotao app = new ExemploBotao();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 3 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 3 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Você pode passar o foco para um determinado botão assim que pressionar a
tecla enter, Com o comando getRootPane().setDefaultButton(). Basta digitar
o comando getRootPane().setDefaultButton(botao);
botão é o nome do botão que você definiu no programa, nesse exemplo definir
o último botão.
Quando você pressionar a tecla Enter o botão que receberá o foco piscará.
Veja o resultado:
botao1.setForeground(Color.blue);
botao2.setForeground(Color.green);
botao3.setForeground(Color.red);
botao4.setForeground(Color.pink);
Resultado do programa:
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 3 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Você também pode definir uma cor para letra conforme seu gosto usando essa
linha caixa.setForeground(new Color(115,99,128));
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 3 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A vantagem de usar uma caixa de texto tipo máscara é que o usuário é forçado
a digitar os dados no formato especificado. O controle não aceita conteúdo que
não siga os padrões predefinidos.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 3 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Obtida a tabela vamos ver essa classe em ação. O aplicativo seguinte exibe
quatro caixas de texto na qual deve ser digitado o CEP, TELEFONE, CPF e
uma DATA qualquer.
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
public class ExemploJFormattedTextField extends JFrame{
JLabel rotulocep,rotulotel,rotulocpf,rotulodata;
JFormattedTextField cep,tel, cpf, data;
MaskFormatter mascaracep,mascaratel, mascaracpf, mascaradata;
public ExemploJFormattedTextField(){
super("Exemplo com JFormattedTextField");
Container tela = getContentPane();
setLayout(null);
try{
mascaracep = new MaskFormatter("#####-###");
mascaratel = new MaskFormatter("(##)####-####");
mascaracpf = new MaskFormatter("#########-##");
mascaradata = new MaskFormatter("##/##/####");
mascaracep.setPlaceholderCharacter(‘_’);
mascaratel.setPlaceholderCharacter(‘_’);
mascaracpf.setPlaceholderCharacter(‘_’);
mascaradata.setPlaceholderCharacter(‘_’);
}
catch(ParseException excp){}
cep.setBounds(150,40,100,20);
tel.setBounds(150,80,100,20);
cpf.setBounds(150,120,100,20);
data.setBounds(150,160,100,20);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 3 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
tela.add(rotulocep);
tela.add(rotulotel);
tela.add(rotulocpf);
tela.add(rotulodata);
tela.add(cep);
tela.add(tel);
tela.add(cpf);
tela.add(data);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploJFormattedTextField app = new ExemploJFormattedTextField();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 3 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
cep.setForeground(Color.blue);
tel.setForeground(Color.red);
cpf.setForeground(Color.green);
data.setForeground(new Color(255,128,128));
cep.setBackground(Color.yellow);
tel.setBackground(Color.yellow);
cpf.setBackground(new Color(255,255,204));
data.setBackground(new Color(255,255,204));
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 4 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Exemplo:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotaoSair extends JFrame{
JButton botaosair;
public ExemploBotaoSair(){
super("Exemplo com JButton");
Container tela = getContentPane();
setLayout(null);
botaosair = new JButton ("Sair");
botaosair.setBounds(100,50,100,20);
botaosair.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
);
tela.add(botaosair);
setSize(300, 150);
setVisible(true);
}
public static void main(String args[]){
ExemploBotaoSair app = new ExemploBotaoSair();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 4 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Use sempre essa lista para fazer qualquer botão funcionar ou chama algum
evento:
nomebotao.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
}
}
);
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SenhaDigitada extends JFrame{
JPasswordField caixa;
JLabel rotulo, exibir;
JButton mostrar;
public SenhaDigitada(){
super("Exemplo com JPasswordField");
Container tela = getContentPane();
setLayout(null);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 4 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 4 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Veja o exemplo:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Soma extends JFrame{
JLabel rotulo1, rotulo2,exibir;
JTextField texto1,texto2;
JButton somar;
public Soma(){
super("Exemplo de soma");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel("1º Número: ");
rotulo2 = new JLabel("2º Número: ");
texto1 = new JTextField(5);
texto2 = new JTextField(5);
exibir = new JLabel("");
somar = new JButton("Somar");
rotulo1.setBounds(50,20,100,20); rotulo2.setBounds(50,60,100,20);
texto1.setBounds(120,20,200,20); texto2.setBounds(120,60,200,20);
exibir.setBounds(50,120,200,20); somar.setBounds(150,100,80,20);
somar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
int numero1,numero2,soma;
soma=0;
numero1 = Integer.parseInt(texto1.getText());
numero2 = Integer.parseInt(texto2.getText());
soma = numero1 + numero2;
exibir.setVisible(true);
exibir.setText("A soma é: "+soma);
}
}
);
exibir.setVisible(false);
tela.add(rotulo1); tela.add(rotulo2);
tela.add(texto1); tela.add(texto2);
tela.add(exibir); tela.add(somar);
setSize(400, 250);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 4 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
setVisible(true);
}
public static void main(String args[]){
Soma app = new Soma();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Foram declaradas três variáveis do tipo inteira: int numero1, numero2, soma;
Foi atribuído zero a variável soma, para a variável ser iniciada vazia: soma=0;
Como texto1, texto2 são String, melhor dizer texto para armazená-las nas
variáveis numero1 e numero2, será necessário converte a String em números.
numero1 = Integer.parseInt(texto1.getText());
numero2 = Integer.parseInt(texto2.getText());
exibir.setVisible(true);
exibir.setText("A soma é: "+soma);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 4 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
texto1.setText(null); ou texto1.setText(“”);
texto2.setText(null); ou texto2.setText(“”);
texto1.requestFocus();
É atribuído null dentro das caixas, pois nulo significa vazio e requestFocus()
passa o foco para a caixa selecionada pelo usuário.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 4 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Esse aplicativo é só para teste não tem muito que ser explicado, pois a única
coisa diferente é que quando você clica em ocultar os JLabels some e você
clica em exibir os JLabels aparecem novamente na janela.
Isso ocorre por que o comando setVisible(false), oculta e o comando
setVisible(true), exibe mostra na janela. Veja o exemplo:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OcultarExibir extends JFrame{
JLabel rotulo1, rotulo2;
JButton ocultar,exbir;
public OcultarExibir(){
super("Exemplo de ocultar e exibir componente");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel("Rótulo 1"); rotulo2 = new JLabel("Rótulo 2");
ocultar = new JButton("Ocultar "); exbir = new JButton("Exibir ");
rotulo1.setBounds(50,20,100,20); rotulo2.setBounds(50,60,100,20);
ocultar.setBounds(100,100,80,20); exbir.setBounds(250,100,80,20);
ocultar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo1.setVisible(false);
rotulo2.setVisible(false);
}
}
);
exbir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo1.setVisible(true);
rotulo2.setVisible(true);
}
}
);
tela.add(rotulo1); tela.add(rotulo2);
tela.add(ocultar); tela.add(exbir);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
OcultarExibir app = new OcultarExibir();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 4 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DesabilitarHabilitar extends JFrame{
JLabel rotulo1, rotulo2;
JButton desabilitar,habilitar;
public DesabilitarHabilitar(){
super("Exemplo de Desabilitar e Habilitar componentes");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel("Rótulo 1"); rotulo2 = new JLabel("Rótulo 2");
desabilitar = new JButton("Desabilitar"); habilitar = new JButton("Habilitar");
rotulo1.setBounds(50,20,100,20); rotulo2.setBounds(50,60,100,20);
desabilitar.setBounds(80,100,100,20); habilitar.setBounds(250,100,100,20);
desabilitar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo1.setEnabled(false);
rotulo2.setEnabled(false);
}
}
);
habilitar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo1.setEnabled(true);
rotulo2.setEnabled(true);
}
}
);
tela.add(rotulo1); tela.add(rotulo2);
tela.add(desabilitar); tela.add(habilitar);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
DesabilitarHabilitar app = new DesabilitarHabilitar();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 4 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 4 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
exibir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo.setText(“o estado é: “+lista.getSelectedValue().toString());
} } );
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 5 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 5 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
lista.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
Veja que agora a lista permite que vários itens sejam selecionados. A outra
modificação aconteceu no evento do botão exibir:
exibir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
Object selecionados[] = lista.getSelectedValues();
String resultados = "Valores selecionados:\n";
for(int i=0;i<selecionados.length;i++)
resultados += selecionados[i].toString()+"\n";
JOptionPane.showMessageDialog(null,resultados);
} } );
Cada vez que selecionados jogar um item dentro de resultado, cada item cada
item vai com a opção de pular uma linha por isso os itens são exibidos um em
baixo do outro.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 5 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Component
Window
J Component
Frame
JComboBox
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 5 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJComboBox extends JFrame{
JComboBox lista;
String cidades[] = {"Rio de Janeiro","São Paulo","Minas Gerais","Espírito
Santo","Bahia","Pernambuco","Rio Grande do Sul","Acre"};
JButton exibir;
JLabel rotulo;
public ExemploJComboBox(){
super("Exemplo de JComboBox");
Container tela = getContentPane();
setLayout(null);
exibir = new JButton("Exibir");
rotulo = new JLabel("");
lista = new JComboBox(cidades);
lista.setMaximumRowCount(5);
lista.setBounds(50,50,150,30);
exibir.setBounds(270,50,100,30);
rotulo.setBounds(50,150,200,30);
exibir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo.setText("o estado é: "+lista.getSelectedItem().toString()); } } );
tela.add(lista);
tela.add(exibir);
tela.add(rotulo);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploJComboBox app = new ExemploJComboBox();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 5 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
usamos anteriormente podem ser aplicadas quando estiver lidando com caixas
de combinação. O primeiro passo foi declarar um objeto da classe JComboBox:
JComboBox Lista;
lista.setMaximumRowCount(5);
O processo usado para exibir o item selecionado é o mesmo que usamos para
as caixas de listagem.
exibir.addActionListener(
new ActionListener(){public void actionPerformed(ActionEvent e){
rotulo.setText("o estado é: “+lista.getSelectedItem().toString());
}});
tela.add(lista);
tela.add(exibir);
tela.add(rotulo);
setSize(400, 250);
setVisible(true);
}
Se você experimentou com o exemplo anterior deve ter percebido que a caixa
de combinação é somente leitura, ou seja, estamos limitados aos itens
disponíveis para a escolha.
Existe, porém, uma forma de permitir que o usuário digite o valor desejado em
uma caixa de combinação. Basta efetuar uma chamada ao método setEditable
fornecendo o valor true como argumento:
lista.setEditable(true);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 5 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJComboBox2 extends JFrame{
JComboBox lista;
String cidades[] = {"Rio de Janeiro","São Paulo","Minas Gerais","Espírito
Santo","Bahia","Pernambuco","Rio Grande do Sul","Acre"};
JButton exibir;
JLabel rotulo;
public ExemploJComboBox2(){
super("Exemplo de JComboBox");
Container tela = getContentPane();
setLayout(null);
exibir = new JButton("Exibir");
rotulo = new JLabel("");
lista = new JComboBox(cidades);
lista.setEditable(true);
lista.setMaximumRowCount(5);
lista.setBounds(50,50,150,30);
exibir.setBounds(270,50,100,30);
rotulo.setBounds(50,150,200,30);
exibir.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo.setText("o estado é: "+lista.getSelectedItem().toString());
}});
tela.add(lista);
tela.add(exibir);
tela.add(rotulo);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploJComboBox2 app = new ExemploJComboBox2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} }
Agora o usuário será capaz de escolher um dos itens disponíveis ou digitar sua
escolha. É comum em campos editáveis o pressionamento da tecla enter após
a entrada da informação no campo. Desse forma, é importante efetuar uma
chamada ao método addActionListener da caixa de combinação e definir o
procedimento a ser efetuado. O trecho do código seguinte mostra como exibir o
valor que o usuário acaba de informar:
exibir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo.setText("o estado é: "+lista.getSelectedItem().toString());
}
}
);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 5 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJCheckBox extends JFrame{
JCheckBox primeira,segunda,terceira,quarta,quinta;
JLabel vazio;
public ExemploJCheckBox(){
super("Exemplo de um JCheckBox");
Container tela = getContentPane();
tela.setLayout(null);
JLabel rotulo = new JLabel("Quais suas linguagens favoritas? ");
rotulo.setBounds(40,30,200,20);
primeira = new JCheckBox("Java");
primeira.setMnemonic(KeyEvent.VK_J);
primeira.setBounds(40,60,60,20);
segunda = new JCheckBox("C++");
segunda.setMnemonic(KeyEvent.VK_C);
segunda.setBounds(100,60,60,20);
terceira = new JCheckBox("Delphi");
terceira.setMnemonic(KeyEvent.VK_D);
terceira.setBounds(160,60,60,20);
quarta = new JCheckBox("Visual Basic");
quarta.setMnemonic(KeyEvent.VK_V);
quarta.setBounds(230,60,100,20);
quinta = new JCheckBox("Python");
quinta.setMnemonic(KeyEvent.VK_P);
quinta.setBounds(335,60,70,20);
JButton botao = new JButton("Exibir");
botao.setBounds(200,150,100,20);
vazio = new JLabel("");
vazio.setBounds(100,200,600,20);
botao.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
String escolhas = "";
if (primeira.isSelected() ==true)
escolhas = escolhas + primeira.getText();
if (segunda.isSelected() ==true)
escolhas = escolhas +" "+segunda.getText();
if (terceira.isSelected() ==true)
escolhas = escolhas +" "+terceira.getText();
if (quarta.isSelected() ==true)
escolhas = escolhas +" "+quarta.getText();
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 5 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
if (quinta.isSelected() ==true)
escolhas = escolhas+" "+quinta.getText();
vazio.setText("Você escolheu: "+escolhas);}});
tela.add(rotulo);
tela.add(primeira);
tela.add(segunda);
tela.add(terceira);
tela.add(quarta);
tela.add(quinta);
tela.add(botao);
tela.add(vazio);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploJCheckBox app = new ExemploJCheckBox();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Durante a análise do código veremos como isso foi possível. Por ora, execute o
aplicativo, selecione as opções desejadas e clique no botão. Veja se o
resultado confere com sua escolha.
JCheckBox primeira,segunda,terceira,quarta,quinta;
Mais adiante você entenderá por que essa variável precisa ser global. Em
seguida temos a criação de cinco caixas de seleção. Veja o código para a
primeira:
primeira = new JCheckBox("Java");
segunda = new JCheckBox("C++");
terceira = new JCheckBox("Delphi");
quarta = new JCheckBox("Visual Basic");
quinta = new JCheckBox("Python");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 5 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
botao.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
String escolhas = "";
if (primeira.isSelected() ==true)
escolhas = escolhas + primeira.getText();
if (segunda.isSelected() ==true)
escolhas = escolhas +" "+segunda.getText();
if (terceira.isSelected() ==true)
escolhas = escolhas +" "+terceira.getText();
if (quarta.isSelected() ==true)
escolhas = escolhas +" "+quarta.getText();
if (quinta.isSelected() ==true)
escolhas = escolhas+" "+quinta.getText();
vazio.setText("Você escolheu: "+escolhas);}});
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 5 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJCheckBox2 extends JFrame{
JCheckBox primeira,segunda,terceira,quarta,quinta;
public ExemploJCheckBox2(){
super("Exemplo de um JCheckBox");
Container tela = getContentPane();
tela.setLayout(null);
primeira = new JCheckBox("Java");
segunda = new JCheckBox("C++");
terceira = new JCheckBox("Delphi");
quarta = new JCheckBox("Visual Basic");
quinta = new JCheckBox("Python");
primeira.setMnemonic(KeyEvent.VK_J);
segunda.setMnemonic(KeyEvent.VK_C);
terceira.setMnemonic(KeyEvent.VK_D);
quarta.setMnemonic(KeyEvent.VK_V);
quinta.setMnemonic(KeyEvent.VK_P);
primeira.setBounds(40,60,60,20);
segunda.setBounds(100,60,60,20);
terceira.setBounds(160,60,60,20);
quarta.setBounds(230,60,100,20);
quinta.setBounds(335,60,70,20);
primeira.setSelected(true);
tela.add(primeira);
tela.add(segunda);
tela.add(terceira);
tela.add(quarta);
tela.add(quinta);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploJCheckBox2 app = new ExemploJCheckBox2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Utilize o método setSelected(true) para a caixa de seleção desejada:
primeira.setSelected(true);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 6 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
primeira.setForeground(Color.blue);
segunda.setForeground(Color.red);
terceira.setForeground(Color.green);
quarta.setForeground(Color.yellow);
quinta.setForeground(Color.white);
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploRadioButton extends JFrame{
JRadioButton primeira,segunda,terceira,quarta,quinta;
JLabel rotulo,rotulo2;
JButton exibir;
ButtonGroup grupo;
public ExemploRadioButton(){
super("Exemplo de um JRadioButton");
Container tela = getContentPane();
tela.setLayout(null);
rotulo = new JLabel("Escolha uma cidade: ");
rotulo.setBounds(50,20,200,20);
rotulo2 = new JLabel("");
rotulo2.setBounds(150,240,400,20);
exibir = new JButton ("Exibir");
exibir.setBounds(200,200,120,20);
primeira = new JRadioButton("Rio de Janeiro");
segunda = new JRadioButton("São Paulo");
terceira = new JRadioButton("Minas Gerais");
quarta = new JRadioButton("Amazonas");
quinta = new JRadioButton("Rio Grande do Sul");
primeira.setBounds(50,50,120,20);
segunda.setBounds(50,80,120,20);
terceira.setBounds(50,110,120,20);
quarta.setBounds(50,140,120,20);
quinta.setBounds(50,170,200,20);
primeira.setMnemonic(KeyEvent.VK_J);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 6 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
segunda.setMnemonic(KeyEvent.VK_C);
terceira.setMnemonic(KeyEvent.VK_D);
quarta.setMnemonic(KeyEvent.VK_V);
quinta.setMnemonic(KeyEvent.VK_P);
public class ExemploRadioButton extends JFrame{
JRadioButton primeira,segunda,terceira,quarta,quinta;
JLabel rotulo,rotulo2;
JButton exibir;
ButtonGroup grupo;
grupo.add(primeira);
grupo.add(segunda);
grupo.add(terceira);
grupo.add(quarta);
grupo.add(quinta);
exibir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
if (primeira.isSelected() ==true)
rotulo2.setText("A cidade escolhida foi: "+primeira.getText());
if (segunda.isSelected() ==true)
rotulo2.setText("A cidade escolhida foi: "+segunda.getText());
if (terceira.isSelected() ==true)
rotulo2.setText("A cidade escolhida foi: "+terceira.getText());
if (quarta.isSelected() ==true)
rotulo2.setText("A cidade escolhida foi: "+quarta.getText());
if (quinta.isSelected() ==true)
rotulo2.setText("A cidade escolhida foi: "+quinta.getText());}});
tela.add(rotulo);
tela.add(primeira);
tela.add(segunda);
tela.add(terceira);
tela.add(quarta);
tela.add(quinta);
tela.add(exibir);
tela.add(rotulo2);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploRadioButton app = new ExemploRadioButton();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 6 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Explicando o aplicativo:
Para adicionar um botão ao grupo, basta efetuar uma chamada ao metodo add
da classe ButtonGroup. Veja:
grupo.add(primeira);
grupo.add(segunda);
grupo.add(terceira);
grupo.add(quarta);
grupo.add(quinta);
É preciso, porém manter em mente que a classe ButtonGroup não é um
contêiner para objetos. Essa classe serve apenas ao propósito de agrupar os
botões para que somente um possa ser selecionado por uma vez.
Se caso o usuário quiser colocar um botão padrão, aquele que já esteja
marcado quando iniciar a janela use: primeiro.setSelected(true);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 6 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploComboCheckRadio extends JFrame{
JLabel rotulo1, rotulo2, rotulo3,texto;
JCheckBox negrito,italico,normal,negritoitalico;
JRadioButton tam1,tam2,tam3,tam4;
ButtonGroup grupo;
String cor[] = {"Sem Cor", "Vermelho", "Azul",
"Verde","Amarelo","Branco","Preto"};
JComboBox lista;
Integer estilo, tamfonte;
public ExemploComboCheckRadio(){
super("Exemplo Combo Check Radio BOX");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel("Cor");
rotulo2 = new JLabel("Estilo");
rotulo3 = new JLabel("Tamanho");
texto = new JLabel("Programa feito em Java");
lista = new JComboBox(cor);
lista.setMaximumRowCount(7);
negrito = new JCheckBox("Negrito");
italico = new JCheckBox("Italico");
normal = new JCheckBox("Normal");
negritoitalico = new JCheckBox("Negrito Itálico");
tam1 = new JRadioButton("12");
tam2 = new JRadioButton("14");
tam3 = new JRadioButton("16");
tam4 = new JRadioButton("18");
grupo = new ButtonGroup();
grupo.add(tam1);
grupo.add(tam2);
grupo.add(tam3);
grupo.add(tam4);
rotulo1.setBounds(40,20,70,20);
rotulo2.setBounds(200,20,70,20);
rotulo3.setBounds(300,20,70,20);
texto.setBounds(100,200,300,20);
lista.setBounds(40,50,150,20);
negrito.setBounds(200,50,100,20);
italico.setBounds(200,70,100,20);
normal.setBounds(200,90,100,20);
negritoitalico.setBounds(200,110,150,20);
tam1.setBounds(350,50,100,20);
tam2.setBounds(350,70,100,20);
tam3.setBounds(350,90,100,20);
tam4.setBounds(350,110,100,20);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 6 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
tamfonte=12;
estilo=Font.PLAIN;
//coloca cor na fonte
lista.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
if (lista.getSelectedItem().toString() == "Sem Cor")
texto.setForeground(Color.black);
if (lista.getSelectedItem().toString() == "Vermelho")
texto.setForeground(Color.red);
if (lista.getSelectedItem().toString() == "Azul")
texto.setForeground(Color.blue);
if (lista.getSelectedItem().toString() == "Verde")
texto.setForeground(Color.green);
if (lista.getSelectedItem().toString() == "Amarelo")
texto.setForeground(Color.yellow);
if (lista.getSelectedItem().toString() == "Branco")
texto.setForeground(Color.white);
if (lista.getSelectedItem().toString() == "Preto")
texto.setForeground(Color.black);}});
//coloca a fonte tamnho 12
tam1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tamfonte=12;
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte tamnho 14
tam2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tamfonte=14;
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte tamnho 16
tam3.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
tamfonte=16;
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte tamnho 18
tam4.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
tamfonte=18;
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte em negrito
negrito.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
estilo=Font.BOLD;
normal.setSelected(false);
italico.setSelected(false);
negritoitalico.setSelected(false);
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte em italico
italico.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 6 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
estilo=Font.ITALIC;
normal.setSelected(false);
negrito.setSelected(false);
negritoitalico.setSelected(false);
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte normal
normal.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
estilo=Font.PLAIN;
negrito.setSelected(false);
italico.setSelected(false);
negritoitalico.setSelected(false);
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte em negrito e italico
negritoitalico.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent e){
estilo=Font.BOLD+Font.ITALIC;
negrito.setSelected(false);
italico.setSelected(false);
normal.setSelected(false);
texto.setFont(new Font("",estilo,tamfonte));}});
tela.add(rotulo1); tela.add(rotulo2); tela.add(rotulo3);
tela.add(texto);
tela.add(negrito); tela.add(italico);
tela.add(normal); tela.add(negritoitalico);
tela.add(tam1); tela.add(tam2);
tela.add(tam3);tela.add(tam4);
tela.add(lista);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true); }
public static void main(String args[]){
ExemploComboCheckRadio app = new ExemploComboCheckRadio();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 6 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Estilo da fonte
negrito = new JCheckBox("Negrito");
italico = new JCheckBox("Itálico");
normal = new JCheckBox("Normal");
negritoitalico = new JCheckBox("Negrito Itálico");
Tamanho da Fonte:
tam1 = new JRadioButton("12");
tam2 = new JRadioButton("14");
tam3 = new JRadioButton("16");
tam4 = new JRadioButton("18");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 6 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 6 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Quando você selecionar o CheckBox do negrito, ele atribui o estilo negrito (BOLD) a
variável estilo, desmaca o CheckBox do normal, itálico e do negrito itálico, e exibir na
tela o rótulo texto com a fonte negrito.
Quando você selecionar o CheckBox do itálico, ele atribui o estilo itálico (ITALIC) a
variável estilo, desmaca o CheckBox do normal, negrito e do negrito itálico, e exibir na
tela o rótulo texto com a fonte em itálico.
A variável estilo é pública por isso quando você atribui valor nela, todos os métodos
que for utilizá-la exibirá no rótulo o estilo da variável estilo.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 6 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotoesDicas extends JFrame{
JButton botao1,botao2;
public ExemploBotoesDicas(){
super("Exemplo de Botões com Dica");
Container tela = getContentPane();
tela.setLayout(null);
botao1 = new JButton("Olá");
botao2 = new JButton("Sair");
botao1.setBounds(100,50,100,20);
botao2.setBounds(100,100,100,20);
botao1.setToolTipText("Botão usado para abrir algo");
botao2.setToolTipText("Botão que será usado para sair");
tela.add(botao1);
tela.add(botao2);
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploBotoesDicas app = new ExemploBotoesDicas();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 7 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotoesDicas2 extends JFrame{
JButton botao1,botao2;
public ExemploBotoesDicas2(){
super("Exemplo de Botões com Dica");
Container tela = getContentPane();
tela.setLayout(null);
botao1 = new JButton("Olá");
botao2 = new JButton("Sair");
botao1.setBounds(100,50,100,20);
botao2.setBounds(100,100,100,20);
botao1.setToolTipText("Botão usado para abrir algo");
botao2.setToolTipText("Botão que será usado para sair");
UIManager.put("ToolTip.background",SystemColor.info);
tela.add(botao1);
tela.add(botao2);
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploBotoesDicas2 app = new ExemploBotoesDicas2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
UIManager.put("ToolTip.foreground",Color.blue);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 7 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Método Uso
showConfirmDialog Usado para pedir confirmação, ou
seja, o usuário tem a opção de
responder “sim”, “não” ou “cancelar”.
showInputDialog Usado para obter entrada para o
programa.
showMessageDialog Usado para exibir mensagem sobre a
execução de alguma operação.
Exemplo:
JOptionPane.showConfirmDialog(null,”Fechar?”,”Fechar”,JOptionPane.YES_NO_OPTION);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 7 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
JOptionPane.showConfirmDialog(parentComponent,”message”,”title”,optionType);
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotaoSair1 extends JFrame{
JButton botao;
public ExemploBotaoSair1(){
super("Exemplo de Botões com Diálogos de confirmação");
Container tela = getContentPane();
tela.setLayout(null);
botao = new JButton("Sair");
botao.setBounds(100,50,100,20);
botao.setToolTipText("Botão que finaliza a janela");
tela.add(botao);
botao.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
int opcao;
opção=JOptionPane.showConfirmDialog(null,
"Deseja mesmo fechar a janela?",
"Fechar",JOptionPane.YES_NO_OPTION);
if (opcao==JOptionPane.YES_OPTION)
System.exit(0);
}});
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploBotaoSair1 app = new ExemploBotaoSair1();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 7 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Se você clicar em Yes a janela será fechada e caso contrário ela continuará.
Passos para colocar o botão a janela e dicas de botões já foram vistos
anteriomente, e para chamar o caixa de confirmação basta você clicar no sair,
e o evento será executado, método para chamar o evento também já foi visto.
Foi declarada uma variável do tipo inteira com o nome de opção. Essa variável
vai receber a resposta do JOptionPane, e vai armazenar o valor que será
escolhido na caixa de confirmação. E o comando IF, que vai fazer a
comparação se o conteúdo da variável opção for igual
JOptionPane.YES_OPTION, ele retorna a verdadeiro e chama o método
System.exite(0) e finaliza a janela.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 7 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
int opcao;
Object[] botoes = {"Sim","Não"};
opcao = JOptionPane.showOptionDialog(null,
"Deseja mesmo fechar a janela?",
"Fechar",JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,botoes,botoes[0]);
if (opcao==JOptionPane.YES_OPTION)
System.exit(0); }});
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);}
public static void main(String args[]){
ExemploTraduzir app = new ExemploTraduzir();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 7 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 7 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Caixa do InputDialog
Veja a lista:
Import javax.swing.JOptionPane;
public class ExemploInputDialog1{
public static void main(String args[]){
Object linguagens [] = {"Java","Delphi","C++","Visual Basic"};
Object opcao = JOptionPane.showInputDialog(null,"Qual sua
linguagem favorita?","Enquete",
JOptionPane.QUESTION_MESSAGE,
null,linguagens,linguagens[0]);
JOptionPane.showMessageDialog(null,"Você escolheu: "+opcao);
System.exit(0);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 7 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMessagens extends JFrame{
JButton erro, informacao, exclamacao, pergunta, nenhum;
public ExemploDeMessagens(){
super("Exemplo de mensagens");
Container tela = getContentPane();
tela.setLayout(null);
erro = new JButton("Erro");
informacao = new JButton("Informação");
exclamacao = new JButton("Exclamação");
pergunta = new JButton("Pergunta");
nenhum = new JButton("Nenhum");
erro.setBounds(30,20,100,20);
informacao.setBounds(30,50,100,20);
exclamacao.setBounds(30,80,150,20);
pergunta.setBounds(30,110,100,20);
nenhum.setBounds(30,140,100,20);
tela.add(erro);
tela.add(informacao);
tela.add(exclamacao);
tela.add(pergunta);
tela.add(nenhum);
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploDeMessagens app = new ExemploDeMessagens();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 7 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 7 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
18 – Maiúsculas e Minúsculas
Nada como você entrar com os dados em minúsculos e obter sua saída em
maiúsculos, ou vice versa. Para colocar a saída em maiúsculo utilize o método:
toUpperCase(). Observe o aplicativo abaixo:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploMaiusculas extends JFrame{
JButton copiar,limpar;
JLabel rotulo1,rotulo2;
JTextField texto1,texto2;
public ExemploMaiusculas(){
super("Exemplo de saídas maiúsculas");
Container tela = getContentPane();
tela.setLayout(null);
rotulo1 = new JLabel("Nome: ");
rotulo2 = new JLabel("Nome: ");
texto1 = new JTextField(20);
texto2 = new JTextField(20);
copiar = new JButton("Copiar");
limpar = new JButton("Limpar");
rotulo1.setBounds(20,30,50,20);
rotulo2.setBounds(20,60,50,20);
texto1.setBounds(60,30,180,20);
texto2.setBounds(60,60,180,20);
copiar.setBounds(20,130,100,20);
limpar.setBounds(180,130,100,20);
copiar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto2.setText(texto1.getText().toUpperCase());}});
limpar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto1.setText("");
texto2.setText("");
texto1.requestFocus();}});
tela.add(rotulo1);
tela.add(rotulo2);
tela.add(texto1);
tela.add(texto2);
tela.add(copiar);
tela.add(limpar);
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null); }
public static void main(String args[]){
ExemploMaiusculas app = new ExemploMaiusculas();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 8 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploMinusculas extends JFrame{
JButton copiar,limpar;
JLabel rotulo1,rotulo2;
JTextField texto1,texto2;
public ExemploMinusculas(){
super("Exemplo de saídas minúsculas");
Container tela = getContentPane();
tela.setLayout(null);
rotulo1 = new JLabel("Nome: ");
rotulo2 = new JLabel("Nome: ");
texto1 = new JTextField(20);
texto2 = new JTextField(20);
copiar = new JButton("Copiar");
limpar = new JButton("Limpar");
rotulo1.setBounds(20,30,50,20);
rotulo2.setBounds(20,60,50,20);
texto1.setBounds(60,30,180,20);
texto2.setBounds(60,60,180,20);
copiar.setBounds(20,130,100,20);
limpar.setBounds(180,130,100,20);
copiar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String texto;
texto = texto1.getText().toUpperCase();
texto1.setText(texto);
texto2.setText(texto1.getText().toLowerCase());}});
limpar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto1.setText("");
texto2.setText("");
texto1.requestFocus();}});
tela.add(rotulo1);
tela.add(rotulo2);
tela.add(texto1);
tela.add(texto2);
tela.add(copiar);
tela.add(limpar);
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);}
public static void main(String args[]){
ExemploMinusculas app = new ExemploMinusculas();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);} }
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 8 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
O aplicativo abaixo mostra dos tipos de data, somente com números e a outra
com o dia da semana e os meses escritos com o nome.
Vamos ver o aplicativo:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Data extends JFrame{
JLabel rotulo,rotulo2;
int ds,dia,mes,ano;
Calendar data;
String diasemana[]={"Domingo","Segunda - Feira","Terça - Feira","Quarta - Feira",
"Quinta - Feira","Sexta - Feira","Sábado"};
String meses[]={"Janeiro","Fevereiro","Março","Abril","Maio","Junho",
"Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"};
public Data(){
super("Exemplo de Data");
Container tela = getContentPane();
tela.setLayout(null);
rotulo = new JLabel("");
rotulo2 = new JLabel("");
rotulo.setBounds(20,30,280,20);
rotulo2.setBounds(20,60,280,20);
data = Calendar.getInstance();
ds = data.get(Calendar.DAY_OF_WEEK);
dia = data.get(Calendar.DAY_OF_MONTH);
mes = data.get(Calendar.MONTH);
ano = data.get(Calendar.YEAR);
rotulo.setText("Data: "+ds+" "+dia+"/"+(mes+1)+"/"+ano);
rotulo2.setText("Data: "+diasemana[ds-1]+", "+dia+" de "+meses[mes]+" de "+ano);
tela.add(rotulo);
tela.add(rotulo2);
setSize(300, 200);
setVisible(true);
setLocationRelativeTo(null); }
public static void main(String args[]){
Data app = new Data();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 8 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.DecimalFormat;
import javax.swing.Timer;
public class Hora extends JFrame{
JLabel rotulo;
int hh,mm,ss,h;
Calendar hora;
DecimalFormat formato;
public Hora(){
super("Exemplo de Hora");
Container tela = getContentPane();
tela.setLayout(null);
rotulo = new JLabel("");
rotulo.setBounds(20,30,280,20);
ActionListener tarefa = (new ActionListener(){
public void actionPerformed(ActionEvent e){
HORAS();
}
});
javax.swing.Timer time = new javax.swing.Timer(1000,tarefa);
time.start();
tela.add(rotulo);
setSize(300, 200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
Hora app = new Hora();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void HORAS(){
hora = Calendar.getInstance();
hh = hora.get(Calendar.HOUR_OF_DAY);
mm = hora.get(Calendar.MINUTE);
ss = hora.get(Calendar.SECOND);
formato = new DecimalFormat("00");
rotulo.setText("Hora: "+formatar(hh%12)+":"+formatar(mm)+":"+formatar(ss));
}
private String formatar(int num){
formato = new DecimalFormat("00");
return formato.format(num);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 8 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Vamos criar uma classe privada com o nome de HORAS vamos definir os
parâmetros para hora, minutos e segundos.
Depois criar um outra classe privada com o nome de formatar para que você
possa formatar a hora com dois dígitos, e coloca a hora no rótulo com uma
string.
Criar uma ação com o nome de tarefa, que vai chamar a classe privada
HORAS.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 8 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 8 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJTextArea3 extends JFrame{
JLabel rotulo;
JTextArea texto;
JScrollPane painelrolagem;
JPanel painel;
public ExemploJTextArea3(){
super("Exemplo com JTextField");
Container tela = getContentPane();
tela.setLayout(null);
rotulo = new JLabel ("Endereço");
rotulo.setBounds(50,20,100,20);
texto = new JTextArea(10,20);
painelrolagem = new JScrollPane(texto);
painelrolagem.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
painelrolagem.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
painel = new JPanel();
painel.add(painelrolagem);
painel.setBounds(40,40,250,250);
tela.add(rotulo);
tela.add(painel);
setSize(300, 280);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploJTextArea3 app = new ExemploJTextArea3();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 8 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
painelrolagem.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROL
LBAR_ALWAYS);
painelrolagem.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_S
CROLLBAR_ALWAYS);
painel.add(painelrolagem);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 8 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Constante Uso
HORIZONTAL_SCROLL_AS_NEEDED Exibe a barra de rolagem horizontal
somente quando for necessário.
HORIZONTAL_SCROLL_NEVER A barra de rolagem horizontal nunca é
exibida.
HORIZONTAL_SCROLL_ALWAYS Define que a barra de rolagem horizontal
deve ser exibida sempre.
VERTICAL_SCROLL_AS_NEEDED Exibe a barra de rolagem vertical
somente quando for necessário.
VERTICAL _SCROLL_NEVER A barra de rolagem vertical nunca é
exibida.
VERTICAL_SCROLL_ALWAYS Define que a barra de rolagem vertical
deve ser exibida sempre.
Veja a sintaxe:
texto.setLineWrap(true);
texto.setWrapStyleWord(true);
texto.setForeground(Color.blue);
texto.setBackground(Color.yellow);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 8 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMenu extends JFrame{
JMenuBar barra;
JMenu opcoes;
JMenuItem limpar,fonte,sair;
public ExemploDeMenu(){
super("Exemplo de Menus");
Container tela = getContentPane();
tela.setLayout(null);
barra = new JMenuBar();
setJMenuBar(barra);
opcoes = new JMenu("Opções");
barra.add(opcoes);
limpar = new JMenuItem("Limpar");
fonte = new JMenuItem("Fonte");
sair = new JMenuItem("Sair");
limpar.setMnemonic(KeyEvent.VK_L);
fonte.setMnemonic(KeyEvent.VK_F);
sair.setMnemonic(KeyEvent.VK_S);
opcoes.add(limpar);
opcoes.add(fonte);
opcoes.addSeparator();
opcoes.add(sair);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploDeMenu app = new ExemploDeMenu();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 8 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
limpar.setMnemonic(KeyEvent.VK_L);
fonte.setMnemonic(KeyEvent.VK_F);
sair.setMnemonic(KeyEvent.VK_S);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 9 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMenu2 extends JFrame{
JMenuBar barra;
JMenu opcoes,fonte,cor;
JMenuItem limpar,sair,estilo,tamanho,azul,verde,vermelho,amarelo,preto;
public ExemploDeMenu2(){
super("Exemplo de Menus com submenus");
Container tela = getContentPane();
tela.setLayout(null);
barra = new JMenuBar();
setJMenuBar(barra);
opcoes = new JMenu("Opções");
barra.add(opcoes);
limpar = new JMenuItem("Limpar");
fonte = new JMenu("Fonte");
cor = new JMenu("Cor");
azul = new JMenuItem("Azul");
verde = new JMenuItem("Verde");
vermelho = new JMenuItem("Vermelho");
amarelo = new JMenuItem("Amarelo");
preto = new JMenuItem("Preto");
estilo = new JMenuItem("Estilo");
tamanho = new JMenuItem("Tamanho");
sair = new JMenuItem("Sair");
limpar.setMnemonic(KeyEvent.VK_L);
fonte.setMnemonic(KeyEvent.VK_F);
sair.setMnemonic(KeyEvent.VK_S);
cor.setMnemonic(KeyEvent.VK_C);
estilo.setMnemonic(KeyEvent.VK_E);
tamanho.setMnemonic(KeyEvent.VK_T);
opcoes.add(limpar);
opcoes.add(fonte);
opcoes.addSeparator();
opcoes.add(sair);
fonte.add(cor);
fonte.add(estilo);
fonte.add(tamanho);
cor.add(azul);
cor.add(verde);
cor.add(vermelho);
cor.add(amarelo);
cor.add(preto);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploDeMenu2 app = new ExemploDeMenu2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 9 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
JMenu opcoes,fonte,cor;
Observe como o item Fonte do menu
Opções tem uma seta para a direita,
indicando que tem nesse item três
submenus, Cor, Estilo e Tamanho. O
item Cor também possui uma seta
para direita, indicando que nesse item
possui, cinco subitens.
Agora vamos criar o item fonte e cor como JMenu, e os itens azul, verde,
vermelho, amarelo e preto serão criados como JMenuItem, vai indicar que o
JMenuItem é um item do JMenu do item Cor.
fonte = new JMenu("Fonte");
cor = new JMenu("Cor");
azul = new JMenuItem("Azul");
verde = new JMenuItem("Verde");
vermelho = new JMenuItem("Vermelho");
amarelo = new JMenuItem("Amarelo");
preto = new JMenuItem("Preto");
estilo = new JMenuItem("Estilo");
tamanho = new JMenuItem("Tamanho");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 9 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Neste tópico vamos mostrar a técnica que usa as caixas de seleção nos itens
do menu. A vantagem de usar caixas de seleção como itens de menu é que
você pode marcar e desmarcar itens sem a exigência de que no mínimo um
dos itens esteja selecionado.
Caixas de seleção como itens do menu são criadas como instâncias da classe
JCheckBoxMenuItem. As propriedades, métodos e eventos dessa classe são
semelhantes aos da classe JCheckBox, de modo que você não terá nenhuma
dificuldade em usá-la em seus aplicativos.
A listagem seguinte mostra como podemos criar as caixas de seleção, onde
todas podem ser selecionadas:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMenu3 extends JFrame{
JMenuBar barra;
JMenu opcoes,fonte,estilo,cor;
JMenuItem limpar,sair,tamanho,azul,verde,vermelho,amarelo,preto;
JCheckBoxMenuItem normal, negrito, italico, negritoitalico;
public ExemploDeMenu3(){
super("Exemplo de Menus com JChekBoxMenuItem");
Container tela = getContentPane();
tela.setLayout(null);
barra = new JMenuBar();
setJMenuBar(barra);
opcoes = new JMenu("Opções");
barra.add(opcoes);
limpar = new JMenuItem("Limpar");
fonte = new JMenu("Fonte");
cor = new JMenu("Cor");
azul = new JMenuItem("Azul");
verde = new JMenuItem("Verde");
vermelho = new JMenuItem("Vermelho");
amarelo = new JMenuItem("Amarelo");
preto = new JMenuItem("Preto");
estilo = new JMenu("Estilo");
tamanho = new JMenuItem("Tamanho");
normal = new JCheckBoxMenuItem("Normal");
negrito = new JCheckBoxMenuItem("Negrito");
italico = new JCheckBoxMenuItem("Itálico");
negritoitalico = new JCheckBoxMenuItem("Negrito e Itálico");
sair = new JMenuItem("Sair");
opcoes.setMnemonic(KeyEvent.VK_O);
limpar.setMnemonic(KeyEvent.VK_L);
fonte.setMnemonic(KeyEvent.VK_F);
sair.setMnemonic(KeyEvent.VK_S);
cor.setMnemonic(KeyEvent.VK_C);
estilo.setMnemonic(KeyEvent.VK_E);
normal.setMnemonic(KeyEvent.VK_M);
negrito.setMnemonic(KeyEvent.VK_N);
italico.setMnemonic(KeyEvent.VK_I);
negritoitalico.setMnemonic(KeyEvent.VK_C);
tamanho.setMnemonic(KeyEvent.VK_T);
opcoes.add(limpar);
opcoes.add(fonte);
opcoes.addSeparator();
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 9 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
opcoes.add(sair);
cor.add(azul);
cor.add(verde);
cor.add(vermelho);
cor.add(amarelo);
cor.add(preto);
estilo.add(normal);
estilo.add(negrito);
estilo.add(italico);
estilo.add(negritoitalico);
fonte.add(cor);
fonte.add(estilo);
fonte.add(tamanho);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploDeMenu3 app = new ExemploDeMenu3();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 9 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMenu4 extends JFrame{
JMenuBar barra;
JMenu opcoes,fonte,cor,estilo,tamanho;
JMenuItem limpar,sair,azul,verde,vermelho,amarelo,preto;
JCheckBoxMenuItem nomeE[];
ButtonGroup grupoT,grupoE;
JRadioButtonMenuItem tamanhoF[];
String tam[] = {"12","14","16","18"};
String est[] = {"Normal", "Negrito", "Itálico", "Negrito e Itálico"};
public ExemploDeMenu4(){
super("Exemplo de Menus com JRadioButtonMenuItem");
Container tela = getContentPane();
tela.setLayout(null);
barra = new JMenuBar();
setJMenuBar(barra);
opcoes = new JMenu("Opções");
barra.add(opcoes);
limpar = new JMenuItem("Limpar");
fonte = new JMenu("Fonte");
cor = new JMenu("Cor");
azul = new JMenuItem("Azul");
verde = new JMenuItem("Verde");
vermelho = new JMenuItem("Vermelho");
amarelo = new JMenuItem("Amarelo");
preto = new JMenuItem("Preto");
estilo = new JMenu("Estilo");
grupoE = new ButtonGroup();
nomeE = new JCheckBoxMenuItem[4];
for(int i = 0; i < 4; i++){
nomeE[i] = new JCheckBoxMenuItem(est[i]);
estilo.add(nomeE[i]);
grupoE.add(nomeE[i]);
}
tamanho = new JMenu("Tamanho");
grupoT = new ButtonGroup();
tamanhoF = new JRadioButtonMenuItem[4];
for(int i = 0; i < 4; i++){
tamanhoF[i] = new JRadioButtonMenuItem(tam[i]);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 9 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
tamanho.add(tamanhoF[i]);
grupoT.add(tamanhoF[i]);
}
sair = new JMenuItem("Sair");
opcoes.setMnemonic(KeyEvent.VK_O);
limpar.setMnemonic(KeyEvent.VK_L);
fonte.setMnemonic(KeyEvent.VK_F);
sair.setMnemonic(KeyEvent.VK_S);
cor.setMnemonic(KeyEvent.VK_C);
estilo.setMnemonic(KeyEvent.VK_E);
tamanho.setMnemonic(KeyEvent.VK_T);
opcoes.add(limpar);
opcoes.add(fonte);
opcoes.addSeparator();
opcoes.add(sair);
cor.add(azul);
cor.add(verde);
cor.add(vermelho);
cor.add(amarelo);
cor.add(preto);
fonte.add(cor);
fonte.add(estilo);
fonte.add(tamanho);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploDeMenu4 app = new ExemploDeMenu4();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 9 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
1º Passo:
JCheckBoxMenuItem nomeE[];
JRadioButtonMenuItem tamanhoF[];
2º Passo:
ButtonGroup grupoT,grupoE;
3º Passo:
Criamos dois vetores do tipo String que servirão para definimos os valores dos
itens do menu.
4º Passo:
Criar os submenus:
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 9 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
5ª Passo:
Em seguinda inicializamos as referências dos grupos:
6ª Passo:
7º Passo:
Esse laço é executado uma vez para cada um dos valores contidos no vetor
est que no nosso caso são quatro estilo (normal, negrito, itálico, negrito e
itálico). A cada interação atribuímos ao item de menu atual um dos valores do
vetor est, adicionamos o item ao menu Estilo e também ao grupo de botões
grupoE. Lembrando que o primeiro índice do vetor é 0, o segundo é 1, o
terceiro é 2 e o quarto é 3, por isso usamos no for i < 4, quando for satisfeita a
condição o for é encerrado e o menu recebe os estilos.
Esse laço é executado uma vez para cada um dos valores contidos no vetor
tam que no nosso caso são quatro estilo (12, 14, 16, 18). A cada interação
atribuímos ao item de menu atual um dos valores do vetor tam, adicionamos o
item ao menu Tamanho e também ao grupo de botões grupoT. Lembrando
que o primeiro índice do vetor é 0, o segundo é 1, o terceiro é 2 e o quarto é 3,
por isso usamos no for i < 4, quando for satisfeita a condição o for é encerrado
e o menu recebe os tamanhos.
OBS: Quando usamos vetores para criar itens de menus não podemos
adicionar teclas de atalho.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 9 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMenu5 extends JFrame{
JMenuBar barra;
JMenu opcoes,fonte,cor,estilo,tamanho;
JMenuItem limpar,sair,azul,verde,vermelho,amarelo,preto;
JCheckBoxMenuItem nomeE[];
ButtonGroup grupoT,grupoE;
JRadioButtonMenuItem tamanhoF[];
String tam[] = {"12","14","16","18"};
String est[] = {"Normal", "Negrito", "Itálico", "Negrito e Itálico"};
JTextArea texto;
JPanel painel;
JScrollPane rolagem;
int estilofonte, tamfonte;
public ExemploDeMenu5(){
super("Exemplo de Menus executando ações");
Container tela = getContentPane();
tela.setLayout(null);
estilofonte=Font.PLAIN;
tamfonte=12;
barra = new JMenuBar();
setJMenuBar(barra);
opcoes = new JMenu("Opções");
barra.add(opcoes);
limpar = new JMenuItem("Limpar");
fonte = new JMenu("Fonte");
cor = new JMenu("Cor");
azul = new JMenuItem("Azul");
verde = new JMenuItem("Verde");
vermelho = new JMenuItem("Vermelho");
amarelo = new JMenuItem("Amarelo");
preto = new JMenuItem("Preto");
TratadorE tratestilo = new TratadorE();
estilo = new JMenu("Estilo");
grupoE = new ButtonGroup();
nomeE = new JCheckBoxMenuItem[4];
for(int i = 0; i < 4; i++){
nomeE[i] = new JCheckBoxMenuItem(est[i]);
estilo.add(nomeE[i]);
grupoE.add(nomeE[i]);
nomeE[i].addItemListener(tratestilo); }
TratadorT trattamanho = new TratadorT();
tamanho = new JMenu("Tamanho");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 9 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 0 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
repaint();}});
sair.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int resposta;
resposta=JOptionPane.showConfirmDialog(null,"Deseja realmente
sair?","Mensagem do Programa",JOptionPane.YES_NO_OPTION);
if (resposta==6)
System.exit(0);}});
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true); }
public static void main (String args[]){
ExemploDeMenu5 app = new ExemploDeMenu5();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
private class TratadorE implements ItemListener{
public void itemStateChanged(ItemEvent e){
if(nomeE[0].isSelected())
estilofonte= Font.PLAIN;
if(nomeE[1].isSelected())
estilofonte= Font.BOLD;
if(nomeE[2].isSelected())
estilofonte= Font.ITALIC;
if(nomeE[3].isSelected())
estilofonte= Font.BOLD+Font.ITALIC;
texto.setFont(new Font("", estilofonte, tamfonte));
repaint(); } }
private class TratadorT implements ItemListener{
public void itemStateChanged(ItemEvent e){
if(tamanhoF[0].isSelected())
tamfonte= 12;
if(tamanhoF[1].isSelected())
tamfonte= 14;
if(tamanhoF[2].isSelected())
tamfonte= 16;
if(tamanhoF[3].isSelected())
tamfonte= 18;
texto.setFont(new Font("", estilofonte, tamfonte));
repaint(); } }
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 0 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Menu Limpar:
limpar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto.setText("");
texto.requestFocus();}});
Menu Sair:
sair.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int resposta;
resposta=JOptionPane.showConfirmDialog(null,"Deseja realmente
sair?","Mensagem do Programa",JOptionPane.YES_NO_OPTION);
if (resposta==6)
System.exit(0);}});
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 0 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
amarelo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto.setForeground(Color.yellow);
repaint();}});
vermelho.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto.setForeground(Color.red);
repaint();}});
Chama a variável que esta fazendo referência a classe privada que vai
executar a ação do menu:
tamanhoF[i].addItemListener(trattamanho);
nomeE[i].addItemListener(tratestilo); }
OBS: O método repaint(), sempre é chamando nas classes, ele serve para
atualizar o estilo, fonte ou a cor escolhida.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 0 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
mport javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDePopupMenu extends JFrame{
JPopupMenu opcoes;
JMenuItem recortar,copiar,colar;
JTextArea texto;
public ExemploDePopupMenu(){
super("Exemplo de PopupMenu");
Container tela = getContentPane();
tela.setLayout(null);
texto = new JTextArea(10,20);
texto.setBounds(30,30,250,250);
texto.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
if(e.isPopupTrigger())
opcoes.show(e.getComponent(),e.getX(),e.getY()); }});
Tratador tratmenu = new Tratador();
opcoes = new JPopupMenu();
recortar = new JMenuItem("Recortar");
copiar = new JMenuItem("Copiar");
colar = new JMenuItem("Colar");
recortar.setMnemonic(KeyEvent.VK_R);
copiar.setMnemonic(KeyEvent.VK_C);
colar.setMnemonic(KeyEvent.VK_L);
recortar.addActionListener(tratmenu);
copiar.addActionListener(tratmenu);
colar.addActionListener(tratmenu);
opcoes.add(recortar);
opcoes.add(copiar);
opcoes.addSeparator();
opcoes.add(colar);
tela.add(texto);
setSize(320,340);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploDePopupMenu app = new ExemploDePopupMenu();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 0 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
}
private class Tratador implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource()==recortar)
texto.cut();
if(e.getSource()==copiar)
texto.copy();
if(e.getSource()==colar)
texto.paste();
repaint(); }}
}
Quando você executar esse aplicativo, clique com o botão direito na área de
texto e o menu de contexto será exibido. Escolha um dos itens do menu e veja
o resultado obtido.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 0 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBarraDeFerramentas extends JFrame{
JToolBar barra;
JButton direita,esquerda,centralizar,recortar,copiar,colar;
ImageIcon imagens[];
public ExemploBarraDeFerramentas(){
super("Exemplo de Barra de Ferramentas");
Container tela = getContentPane();
tela.setLayout(null);
String icones[]={"imagens/direita.gif","imagens/esquerda.gif",
"imagens/centro.gif","imagens/recortar.gif",
"imagens/copiar.gif","imagens/colar.gif"};
imagens = new ImageIcon[6];
for(int i = 0;i < 6;i++){
imagens[i] = new ImageIcon(icones[i]);}
direita = new JButton(imagens[0]);
esquerda = new JButton(imagens[1]);
centralizar = new JButton(imagens[2]);
recortar = new JButton(imagens[3]);
copiar = new JButton(imagens[4]);
colar = new JButton(imagens[5]);
direita.setToolTipText("Direita (Ctrl+d)");
esquerda.setToolTipText("Esquerda (Ctrl+e)");
centralizar.setToolTipText("Centralizar (Ctrl+z)");
recortar.setToolTipText("Recortar (Ctrl+x)");
copiar.setToolTipText("Copiar (Ctrl+c)");
colar.setToolTipText("Colar (Ctrl+v)");
barra = new JToolBar("Barra de Ferramentas");
UIManager.put("ToolTip.background",SystemColor.info);
UIManager.put("ToolTip.foreground",Color.blue);
barra.setRollover(true);
barra.add(direita);
barra.add(esquerda);
barra.add(centralizar);
barra.addSeparator();
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 0 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
barra.add(recortar);
barra.add(copiar);
barra.add(colar);
barra.setBounds(1,1,260,50);
tela.add(barra);
setSize(320,340);
setLocationRelativeTo(null);
setVisible(true); }
public static void main (String args[]){
ExemploBarraDeFerramentas app = new ExemploBarraDeFerramentas();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Para que este exemplo ficasse bem realista, adicionamos uma barra de menus.
Experimente arrastar a barra de ferramentas.
O nome e o caminho das imagens são definidos como itens do vetor ícones:
String icones[]={"imagens/direita.gif","imagens/esquerda.gif",
"imagens/centro.gif","imagens/recortar.gif",
"imagens/copiar.gif","imagens/colar.gif"};
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 0 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 0 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NovaJanela2 extends JFrame{
JButton abrir;
Inicial segundajanela;
public NovaJanela2(){
super("Abrir uma nova janela");
Container tela = getContentPane();
tela.setLayout(null);
abrir = new JButton("Abrir");
abrir.setBounds(100,50,80,20);
abrir.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
segundajanela = new Inicial(null,"Segunda Janela",true);
segundajanela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
segundajanela.setVisible(true); }});
tela.add(abrir);
setSize(300, 150);
setVisible(true);
setLocationRelativeTo(null);}
public static void main(String args[]){
NovaJanela2 app = new NovaJanela2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}
private class Inicial extends JDialog{
JButton sair;
public Inicial(Frame owner, String title,boolean modal){
super(owner,title,modal);
Container tela1 = getContentPane();
tela1.setLayout(null);
sair = new JButton("Sair");
sair.setBounds(50,50,100,20);
TBsair tsair = new TBsair();
sair.addActionListener(tsair);
tela1.add(sair);
setSize(200,200);
setLocationRelativeTo(null);} }
private class TBsair implements ActionListener{
public void actionPerformed(ActionEvent evento){
int status = JOptionPane.showConfirmDialog(null,"Deseja realmente fechar o
programa?","Mensagem de saída",JOptionPane.YES_NO_OPTION);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 0 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
if (status == JOptionPane.YES_OPTION)
{segundajanela.setVisible(false);
segundajanela.dispose();}}
}
}
Primeira janela Segunda Janela
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 1 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Declaramos a variável que vai fazer referência ao botão sair: JButton sair;
Classe privada Incial: Esta classe herda JDialog. Observe os parâmetros para
seu construtor: public Inicial(Frame owner, String Title, boolean modal);
abrir.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
segundajanela = new Inicial(null,"Segunda Janela",true);
segundajanela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
segundajanela.setVisible(true);
}
}
);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 1 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
segundajanela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Sem muita modificações dos exemplos anteriores, o que tem de diferente é que
quando você clicar em Sim para finalizar a janela secundária, o aplicativo
coloca a janela invisível com o método setVisible(false); e depois retira da
memória com o método dispose().
Janela não-modais são aquelas onde você, pode fazer uso da janela principal.
Exemplo do aplicativo de janela não-modal, veja o exercício
NovaJanela4.java.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 1 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Como a classe JDialog, também podemos criar uma janela com a classe
JFrame, quando você iniciar esse aplicativo, será executada a tela principal
com um botão chamado Abrir, quando você abrir a janela secundária com o
botão Sair, a janela principal fica invisível com o método setVisible(false); e
depois é retirada da memória com o método dispose(), já na janela secundária
quando você clicar em sair uma mensagem será exibida, perguntando se você
quer fechar o aplicativo, caso você responda sim a janela é fechada.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NovaJanela extends JFrame{
JButton abrir;
Inicial segundajanela;
public NovaJanela(){
super("Abrir uma nova janela");
Container tela = getContentPane();
tela.setLayout(null);
abrir = new JButton("Abrir");
abrir.setBounds(100,50,80,20);
abrir.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
segundajanela = new Inicial();
segundajanela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
segundajanela.setVisible(true);
setVisible(false);
dispose();}});
tela.add(abrir);
setSize(300, 150);
setVisible(true);
setLocationRelativeTo(null);}
public static void main(String args[]){
NovaJanela app = new NovaJanela();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}
private class Inicial extends JFrame{
JButton sair;
private Inicial(){
super("Menu Principal...");
Container tela = getContentPane();
tela.setLayout(null);
sair = new JButton("Sair");
sair.setBounds(50,50,100,20);
TBsair tsair = new TBsair();
sair.addActionListener(tsair);
tela.add(sair);
setSize(200,200);
setLocationRelativeTo(null);} }
private class TBsair implements ActionListener{
public void actionPerformed(ActionEvent evento){
int status = JOptionPane.showConfirmDialog(null,"Deseja realmente fechar o
programa?","Mensagem de saída",JOptionPane.YES_NO_OPTION);
if (status == JOptionPane.YES_OPTION)
{segundajanela.setVisible(false);
segundajanela.dispose();}}
} }
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 1 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploSplashScreen extends JFrame{
TelaInicial inicio;
JButton botaosair;
public ExemploSplashScreen(){
super("Exemplo de Splash Screen");
Container tela = getContentPane();
tela.setLayout(null);
inicio = new TelaInicial();
inicio.setVisible(true);
botaosair = new JButton ("Sair");
botaosair.setBounds(100,50,100,20);
botaosair.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0); } } );
tela.add(botaosair);
setSize(300, 150);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploSplashScreen app = new ExemploSplashScreen();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}
public void principal(){
setVisible(true);}
private class TelaInicial extends JWindow{
public TelaInicial(){
Container tela = getContentPane();
tela.setLayout(new FlowLayout(FlowLayout.LEFT,1,1));
ImageIcon imagem = new ImageIcon("imagens/fundo.gif");
JLabel rotulo = new JLabel(imagem);
tela.add(rotulo);
ActionListener fechar = new ActionListener(){
public void actionPerformed(ActionEvent e){
setVisible(false);
dispose();
principal();}};
javax.swing.Timer timer = new javax.swing.Timer(5000,fechar);
timer.start();
pack();
setLocationRelativeTo(null);
} }
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 1 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A tela de splash mostrada na figura é exibida por cinco segundos. Decorrido esse
período, ela será fechada e a janela principal do aplicativo será exibida. Vamos
analisar todo o código começando com a classe TelaInicial:
Esta classe estende JWindow, portanto não terá bordas, barra de títulos ou botões de
sistema: private class TelaInicial extends JWindow
O único proposito deste método é tornar a janela principal visível, uma vez que não
podemos acessa-la a partir da classe TelaInicial.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 1 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Um banco de dados típico é formado por uma ou mais Tabelas. As tabelas, por
sua vez, são formadas por COLUNAS e LINHAS. As COLUNAS, também
chamadas de CAMPOS, servem para dar nome ao espaço reservados a
determinada informação. Já as LINHAS de uma tabela, também chamadas de
REGISTROS ou TUPLAS. São espaços reservados para a informação a ser
armazenada.
No exemplo apresentado em seguida temos três CAMPOS, de nome ID,
NOME e TELEFONE. Os campos dão nome a cada coluna do Banco de Dado
se indicam qual informação será armazenada em cada coluna. Três LINHAS,
contendo informações de três pessoas. Note que, enquanto os campos são
únicos e não se repetem, as linhas são em quantidade quase infinita e podem
se repetir total ou parcialmente.
Nota: Neste caso em particular, as informações do campo ID são geradas pelo próprio
SGBD por meio da autonumeração; portanto, não são inseridas pelo usuários e
também não se repetem.
ID NOME TELEFONE
1 Tulio Maravilha 1234-5678
2 Otavio Mesquita 1234-6789
3 Luiz Pedro 1234-9658
► (AutoNumeração) |
O conjunto apresentado forma uma tabela de nome CADASTRO que, por sua vez,
forma o banco de dados AGENDA.
1) Cria-se um banco de dados, dando um nome a ele. Esse nome vai ajudá-lo a
identificar o tipo de informação que ele contêm. Exemplo de nomes para Banco de
Dados: colecoes, vendas, cadastro, etc. Evitamos o uso de palavras acentuadas e
separadas por espaço, tendo em vista a maior compatibilidade possível. Se necessário
usar mais de uma palavra para nomear o banco de dados, separe-as pelo caractere
UNDERSCORE (sublinhado), como em seguida: Departamento_Pessoal.
2) e 3) Cria-se uma ou mais tabelas, definindo para cada uma delas o nome de cada
coluna e o tipo de dados que ela armazenará. Usando como exemplo, o banco de
dados Departamento_Pessoal, podemos criar as tabelas funcionarios, imposto,
ponto eletronico. Aqui também vale a regra de evitar acentuação na nomeação das
tabelas e seus campos, bem como separar palavras pelo caractere UNDERSCORE
(sublinhado).
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 1 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Note que cada cliente pode fazer mais de um pedido, mais cada pedido só
pode estar relacionado a um cliente. O campo que está sendo usado para
relacionar uma tabela à outra é o Número do Cliente. Se este vínculo não
fosse criado, não haveria como saber qual cliente é determinado pedido, a não
ser que incluíssemos em cada pedido todos os dados do cliente. Com o uso
dos relacionamentos, este procedimento é desnecessário.
27.3 – BD x SGBD
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 1 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
27. 4 – Índices
Tipos de Índices
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 1 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Antes de criar o Banco de Dados, crie uma pasta no raiz C:\, chamada Agenda.
Figura1
Figura2
Com este procedimento o banco de dados Agenda.mdb, precisa de ao menos
uma tabela para pode armazenar informações. A tabela pode ser criada com
ACCESS, Java e SQL. Não feche o MS ACCESS.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 1 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 2 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
chave,
Agora a tabela Cadastro está criada e pronta para receber dados, seja pelo ACCESS,
Java ou SQL.
28 – O que SQL?
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 2 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
MS ACCESS SQL
Texto CHAR
CHAR(n)
VARCHAR
VARCHAR(n)
Sendo “n” um número que identifica o comprimento do campo, ou seja, qual o limite
máximo de caracteres que pode ser armazenado.
Se não for especificado, será igual a 255.
Memorando TEXT
Formato MS ACCESS Formato SQL
BYTE
Byte SMALLINT
Inteiro INTEGER
Inteiro Longo REAL
Número Simples FLOAT
Duplo UNIQUEIDENTIFIER
Código de Replicação DECIMAL ou NUMERIC
Decimal DECIMAL(n) ou NUMERIC(n)
DECIMAL(n,d) ou NUMERIC(n,d)
Sendo “n” é o número máximo de caracteres permitido no campo,
“d” é o número de casas decimais.
Data/Hora DATE, TIME, DATETIME
Moeda MONEY ou CURRENCY
AutoNumeração COUNTER
Sim/Não BIT
Tipos Numéricos
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 2 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
29 – ODBC/JDBC
29.5 – DriverManager
O DriverManager é uma classe pacote Java.sql e serve para:
Fazer a conexão com o banco de dados;
Gerenciar o conjunto de drivers JDBC correspondente;
Controlar o Login;
Controlar as mensagens entre o banco de dados e o driver.
Um programador que utiliza um driver não precisa saber como ele foi
codificado, mas deve saber como carregá-lo para que ele se registre no
DriverManager.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 2 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Figura1
Figura2
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 2 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Figura3
Figura4
Figura5
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 2 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Figura6
Uma fonte de dados ODBC com o nome Agenda, criado conforme o tópico
29.6.
Vejamos a anatomia de uma classe que implementa uma conexão com banco
de dados:
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import java.sql.*;
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 2 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Linha 19 – Esta linha carrega o driver que será usado pela aplicação Java para
realizar a comunicação com o banco de dados.
Linha 22 – Exibe uma mensagem dizendo que a conexão foi estabelecida com
sucesso.
15. try {
16. String url = "jdbc:odbc:Agenda";
17. String usuario = "";
18. String senha = "";
19. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
20. Connection con;
21. con = DriverManager.getConnection(url,usuario,senha);
22. JOptionPane.showMessageDialog(null,"Conexão
estabelecida","Mensagem do
Programa",JOptionPane.INFORMATION_MESSAGE);
23. con.close();
24. }
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 2 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 2 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
E não é só isto, além do nome do campo e do tipo de dados, você pode incluir
as seguintes chaves:
NULL – Não rquerido. O campo não precisa conter dados. Se nada for
especificado, NULL será usado como padrão default.
Vamos criar a Tabela3 usando o PRIMARY KEY, (campo chave), que também
pode ser criado na instrução SQL.
Quase sempre vamos ter um ou mais campos em nossa tabela, que não
podem se repetir. Exemplos de campos que não podem se repetir: nome,
número de código, matrícula, login e etc. Com a palavra chave UNIQUE,
definimos os campos os campos que não admitem dados repetidos:
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 2 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Agora que vimos como CRIAR, ALTERAR e REMOVER tabelas, vamos ver
como incluir dados em uma tabela já existente. Veja a sintaxe:
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 3 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
if ((t6.getText().equals("s")) || (t6.getText().equals("S")))
result = "1";
else if ((t6.getText().equals("n")) || (t6.getText().equals("N")))
result = "0";
Lembretes:
1. Não inseri dados em campos do tipo COUNTER (AutoNumeração).
2. Atenção com os campos que possuem a chave NOT NULL, pois a inserção
de dados é obrigatória.
3. Também será retornado erro caso você defina um campo como PRIMARY
KEY ou UNIQUE e tente entrar com dados repetidos nestes campos.
Agora que possuímos tabelas com dados, podemos usar a instrução SELECT
e cláusula WHERE (onde) para consultas a essas tabelas. Cláusula WHERE
perimte que façamos consultas (SELECT), alterações (UPDATE) e exclusões
(DELETE) com o uso de condições para que a ação seja executada.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 3 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
= igual a
<> diferente de
< menor que
<= menor que ou igual a
> maior que
>= maior que ou igual
Outros exemplos:
Retorna todos os registros que possuam a string João no início do campo:
Exemplo Consultar6.java, listar todos registros que o sobre nome tenha Silva
e todos que o salário seja menor que 500.
SELECT * FROM Tabela1 WHERE Nome LIKE '%Silva%' OR sal < 500
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 3 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A Função IsNull – Retorna os campos que não possuem dados. Lista todos os
campos que estão em branco. Exemplo uma lista de alunos, que nem todos os
alunos possuem telefone. Essa instrução lista esse campos em branco:
WHERE InNull(Telefone)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Consultar8 extends JFrame{
JButton botao;
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3,t4,t5,t6;
String result;
int num;
public Consultar8(){
super("Inclusão de Registro");
Container tela = getContentPane();
tela.setLayout(null);
l1 = new JLabel("Código: "); t1 = new JTextField(5);
l2 = new JLabel("Nome: "); t2 = new JTextField(50);
l3 = new JLabel("Idade: "); t3 = new JTextField(2);
l4 = new JLabel("Data Nasc.: "); t4 = new JTextField(10);
l5 = new JLabel("Salário: "); t5 = new JTextField(15);
l6 = new JLabel("Deficiência: "); t6 = new JTextField(5);
l1.setBounds(20,30,80,20); t1.setBounds(100,30,150,20);
l2.setBounds(20,70,80,20); t2.setBounds(100,70,300,20);
l3.setBounds(20,110,80,20);t3.setBounds(100,110,30,20);
l4.setBounds(20,150,80,20);t4.setBounds(100,150,100,20);
l5.setBounds(20,190,80,20);t5.setBounds(100,190,70,20);
l6.setBounds(20,230,80,20);t6.setBounds(100,230,70,20);
botao = new JButton("Consultar Registro"); botao.setBounds(110,270,150,20);
tela.add(l1);tela.add(t1);
tela.add(l2);tela.add(t2);
tela.add(l3);tela.add(t3);
tela.add(l4);tela.add(t4);
tela.add(l5);tela.add(t5);
tela.add(l6);tela.add(t6);
tela.add(botao);
botao.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 3 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Tabela1 WHERE
Cod="+t1.getText());
rs.next();
t2.setText(rs.getString("Nome"));
t3.setText(rs.getString("Idade"));
t4.setText(rs.getString("Dn"));
t5.setText(rs.getString("Sal"));
num=Integer.parseInt(rs.getString("Def"));
if (num==1)
result = "Sim";
else if (num==0)
result = "Não";
t6.setText(result);
st.close();
con.close();
}
catch(Exception event) {
JOptionPane.showMessageDialog(null,"Conexão não
estabelecida \nPessoa não encontrada","Mensagem do
Programa",JOptionPane.ERROR_MESSAGE);
}
}});
setSize(450, 350);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
Consultar8 app = new Consultar8();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Tabela1 WHERE
Cod="+t1.getText());
Statement st = con.createStatement();
Realiza a consulta que será feita pelo campo Código, chamando o método
executeQuery de Statement:
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 3 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
rs.next();
t2.setText(rs.getString("Nome"));
t3.setText(rs.getString("Idade"));
t4.setText(rs.getString("Dn"));
t5.setText(rs.getString("Sal"));
Resgata o valor do campo Def, converte esse valor para inteiro e armazena na
variável inteira num, declarada no início do aplicativo:
num=Integer.parseInt(rs.getString("Def"));
Utiliza o laço IF para condição, que verifica se o valor da variável num, for igual
a 1, a sentença é verdadeira, logo o conteúdo a ser exibido na caixa de texto
será Sim, caso contrário se o valor for igual a 0, logo a sentença será falsa e o
conteúdo a ser exibido na caixa de texto, será Não.
if (num==1)
result = "Sim";
else if (num==0)
result = "Não";
t6.setText(result);
Caso o usuário entre com o código inválido, o aplicativo exibirá uma mensagem
de texto, informando ao usuário a inválidade.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 3 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Podemos optar por exibir os dados ordenados por um dos campos da tabela:
ASC ou DESC
No campo Sal, se você for adicionar o valor com vírgula coloque o valor entre
aspas simples ex: ‘380,00’
No campo Dn, onde os valores a serem incluídos são datas deve ser usar #23-
05-2004#.
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 3 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
if ((t6.getText().equals("s")) || (t6.getText().equals("S")))
{result = "1";
t6.setText("Sim");}
else if ((t6.getText().equals("n")) || (t6.getText().equals("N")))
{result = "0";
t6.setText("Não");}
Para excluir dados de uma linha inteira de uma tabela, usamos a seguinte
instrução DELETE:
Até agora estamos visualizando nossas listagem no console. Agora vamos ver
uma listagem feita na própria janela. Veja o aplicativo Relatorio.java:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import java.util.*;
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 3 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
public Relatorio(){
super("Agenda - Nomes" );
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
try{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
con = DriverManager.getConnection(url, usuario, senha);
}
catch (Exception e){
JOptionPane.showMessageDialog(null,"Conexão não
estabelecida","Mensagem do Programa",
JOptionPane.ERROR_MESSAGE);
}
buscaTabela();
setSize(600,200);
setVisible(true);
}
public static void main(String args[]){
Relatorio app = new Relatorio();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void buscaTabela(){
Statement st;
ResultSet res;
try{
Vector cabecalho = new Vector();
Vector linhas = new Vector();
st = con.createStatement();
res = st.executeQuery("SELECT * FROM Cadastro ORDER BY Nome");
res.next();
ResultSetMetaData rsmd = res.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
cabecalho.addElement(rsmd.getColumnName(i));
do{
linhas.addElement(proximaLinha(res,rsmd));
}
while (res.next());
tabela = new JTable(linhas,cabecalho);
JScrollPane scroller = new JScrollPane( tabela );
getContentPane().add(scroller, BorderLayout.CENTER);
validate();
st.close();
}
catch (SQLException sqlex){
}
}
private Vector proximaLinha(ResultSet rs, ResultSetMetaData rsmd){
Vector LinhaAtual = new Vector();
try{
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
switch(rsmd.getColumnType(i)){
case Types.VARCHAR: LinhaAtual.addElement(rs.getString(i));
break;
case Types.TIMESTAMP: LinhaAtual.addElement(rs.getDate(i));
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 3 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
break;
case Types.NUMERIC: LinhaAtual.addElement(new Long(rs.getLong(i)));
break;
}
}
catch(SQLException e){
}
return LinhaAtual;
}
}
Aplicativo Relatorio.java em execução
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 3 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
buscaTabela();
Statement st;
ResultSet res;
st = con.createStatement();
res.next();
10. Inicia um loop. O objeto das linhas seguintes é montar a tabela com seus
cabeçalhos:
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 4 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
do{
linhas.addElement(proximaLinha(res,rsmd));
}
while (res.next());
tabela = new JTable(linhas,cabecalho);
JScrollPane scroller = new JScrollPane( tabela );
getContentPane().add(scroller, BorderLayout.CENTER);
validate();
12. Por fim, estrutura switch…case verifica o tipo de dados e utilize a forma
mais apropriada para obtê-los (getString() para textos, getDate() para
data/hora, getLong() para números):
switch(rsmd.getColumnType(i)){
case Types.VARCHAR: LinhaAtual.addElement(rs.getString(i));
break;
case Types.TIMESTAMP: LinhaAtual.addElement(rs.getDate(i));
break;
case Types.NUMERIC: LinhaAtual.addElement(new Long(rs.getLong(i)));
break;
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 4 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Verificar quais Tipos de Dados podem ser utilizados para exibir a saída de
dados da tabela.
SELECT Tabela1.Cod,Tabela1.Nome,Tabela1.Idade,Tabela1.Dn,Tabela1.Sal,
Tabela1.Def,Cadastro.Telefone_1,Cadastro.Telefone_2,Cadastro.Celular
WHERE Cadastro.Nome=Tabela1.Nome
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 4 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
mport javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Alterar extends JFrame{
JButton botao, botao2;
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3,t4,t5,t6;
String result;
int num;
Alterar(){
super("Alteração de Registro");
Container tela = getContentPane();
tela.setLayout(null);
l1 = new JLabel("Código: "); t1 = new JTextField(5);
l2 = new JLabel("Nome: "); t2 = new JTextField(50);
l3 = new JLabel("Idade: "); t3 = new JTextField(2);
l4 = new JLabel("Data Nasc.: "); t4 = new JTextField(10);
l5 = new JLabel("Salário: "); t5 = new JTextField(15);
l6 = new JLabel("Deficiência: "); t6 = new JTextField(5);
l1.setBounds(20,30,80,20); t1.setBounds(100,30,150,20);
l2.setBounds(20,70,80,20); t2.setBounds(100,70,300,20);
l3.setBounds(20,110,80,20);t3.setBounds(100,110,30,20);
l4.setBounds(20,150,80,20);t4.setBounds(100,150,100,20);
l5.setBounds(20,190,80,20);t5.setBounds(100,190,70,20);
l6.setBounds(20,230,80,20);t6.setBounds(100,230,70,20);
botao = new JButton("Consultar Registro"); botao.setBounds(20,270,150,20);
botao2 = new JButton("Alterar Registro"); botao2.setBounds(200,270,150,20);
tela.add(l1);tela.add(t1);
tela.add(l2);tela.add(t2);
tela.add(l3);tela.add(t3);
tela.add(l4);tela.add(t4);
tela.add(l5);tela.add(t5);
tela.add(l6);tela.add(t6);
tela.add(botao);tela.add(botao2);
botao.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Tabela2 WHERE
Cod="+t1.getText());
rs.next();
t2.setText(rs.getString("Nome"));
t3.setText(rs.getString("Idade"));
t4.setText(rs.getString("Dn"));
t5.setText(rs.getString("Sal"));
num=Integer.parseInt(rs.getString("Def"));
if (num==1)
result = "Sim";
else if (num==0)
result = "Não";
t6.setText(result);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 4 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \nPessoa
não encontrada","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
}});
botao2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
if ((t6.getText().equals("s")) || (t6.getText().equals("S")))
{result = "1";
t6.setText("Sim");}
else if ((t6.getText().equals("n")) || (t6.getText().equals("N")))
{result = "0";
t6.setText("Não");}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Alterar2 extends JFrame{
JButton botao;
JLabel l1;
JTextField t1;
Alterar2(){
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 4 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
super("Alteração de Registro");
Container tela = getContentPane();
tela.setLayout(null);
l1 = new JLabel("Entre com o valor do novo salário: ");
t1 = new JTextField(10);
l1.setBounds(20,30,250,20); t1.setBounds(20,50,80,20);
botao = new JButton("Alterar Valores"); botao.setBounds(150,100,150,20);
tela.add(botao);
tela.add(l1);tela.add(t1);
tela.add(botao);
botao.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
st.executeUpdate("UPDATE Tabela2 SET Def="+t1.getText());
JOptionPane.showMessageDialog(null,"Registros Alterado com Sucesso","Mensagem
do Programa",JOptionPane.INFORMATION_MESSAGE);
t1.requestFocus();
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \nPessoa
não encontrada","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
}});
setSize(450,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
Alterar2 app = new Alterar2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
public class Consultar extends JFrame{
String result;
public Consultar(){
super("Consulta de Registros");
Container tela = getContentPane();
tela.setLayout(null);
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 4 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Tabela1");
while (rs.next()){
System.out.println("Codigo: "+rs.getString("Cod")+" ");
System.out.println("Nome: "+rs.getString("Nome")+" ");
System.out.println("Idade: "+rs.getString("Idade")+" ");
System.out.println("Data Nasc.: "+rs.getString("Dn")+" ");
System.out.println("Salario: "+rs.getString("Sal")+" ");
System.out.println("Deficiencia: "+rs.getString("Def")+" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
}
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \n
Comandos Digitados Inválidos","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
setSize(450, 350);
}
public static void main(String args[]){
Consultar app = new Consultar();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
public class Consultar2 extends JFrame{
String result;
JTable tabela;
public Consultar2(){
super("Consulta de Registros");
Container tela = getContentPane();
tela.setLayout(null);
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Cadastro");
while (rs.next()){
System.out.println("Nome: "+rs.getString("Nome")+" ");
System.out.println("Tel 1: "+rs.getString("Telefone_1")+" ");
System.out.println("Tel 2: "+rs.getString("Telefone_2")+" ");
System.out.println("Celular.: "+rs.getString("Celular")+" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 4 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \n
Comandos Digitados Inválidos","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
setSize(450, 350);
}
public static void main(String args[]){
Consultar2 app = new Consultar2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
public class Consultar3 extends JFrame{
String result;
public Consultar3(){
super("Consulta de Registros");
Container tela = getContentPane();
tela.setLayout(null);
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Tabela1 WHERE NOT
Cod>5");
while (rs.next()){
System.out.println("Codigo: "+rs.getString("Cod")+" ");
System.out.println("Nome: "+rs.getString("Nome")+" ");
System.out.println("Idade: "+rs.getString("Idade")+" ");
System.out.println("Data Nasc.: "+rs.getString("Dn")+" ");
System.out.println("Salario: "+rs.getString("Sal")+" ");
System.out.println("Deficiencia: "+rs.getString("Def")+" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
}
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \n
Comandos Digitados Inválidos","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
setSize(450, 350);
}
public static void main(String args[]){
Consultar3 app = new Consultar3();
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 4 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
public class Consultar4 extends JFrame{
String result;
public Consultar4(){
super("Consulta de Registros");
Container tela = getContentPane();
tela.setLayout(null);
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Tabela1 WHERE Nome
LIKE '%Silva%'");
while (rs.next()){
System.out.println("Codigo: "+rs.getString("Cod")+" ");
System.out.println("Nome: "+rs.getString("Nome")+" ");
System.out.println("Idade: "+rs.getString("Idade")+" ");
System.out.println("Data Nasc.: "+rs.getString("Dn")+" ");
System.out.println("Salario: "+rs.getString("Sal")+" ");
System.out.println("Deficiencia: "+rs.getString("Def")+" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
}
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \n
Comandos Digitados Inválidos","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
setSize(450, 350);
}
public static void main(String args[]){
Consultar4 app = new Consultar4();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
public class Consultar5 extends JFrame{
String result;
public Consultar5(){
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 4 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
super("Consulta de Registros");
Container tela = getContentPane();
tela.setLayout(null);
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Tabela1 WHERE Sal <=500
AND Dn < #01-01-1979#");
while (rs.next()){
System.out.println("Codigo: "+rs.getString("Cod")+" ");
System.out.println("Nome: "+rs.getString("Nome")+" ");
System.out.println("Idade: "+rs.getString("Idade")+" ");
System.out.println("Data Nasc.: "+rs.getString("Dn")+" ");
System.out.println("Salario: "+rs.getString("Sal")+" ");
System.out.println("Deficiencia: "+rs.getString("Def")+" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
}
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \n
Comandos Digitados Inválidos","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
setSize(450, 350);
}
public static void main(String args[]){
Consultar5 app = new Consultar5();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
public class Consultar6 extends JFrame{
String result;
public Consultar6(){
super("Consulta de Registros");
Container tela = getContentPane();
tela.setLayout(null);
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 4 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
public class Consultar7 extends JFrame{
String result;
public Consultar7(){
super("Consulta de Registros");
Container tela = getContentPane();
tela.setLayout(null);
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Tabela1,Cadastro WHERE
Tabela1.Nome=Cadastro.Nome");
while (rs.next()){
System.out.println("Codigo: "+rs.getString("Cod")+" ");
System.out.println("Nome: "+rs.getString("Nome")+" ");
System.out.println("Idade: "+rs.getString("Idade")+" ");
System.out.println("Data Nasc.: "+rs.getString("Dn")+" ");
System.out.println("Salario: "+rs.getString("Sal")+" ");
System.out.println("Deficiencia: "+rs.getString("Def")+" ");
System.out.println("Telefone 1: "+rs.getString("Telefone_1")+" ");
System.out.println("Telefone 1: "+rs.getString("Telefone_2")+" ");
System.out.println("Celular: "+rs.getString("Celular")+" ");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 5 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
}
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \n
Comandos Digitados Inválidos","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
setSize(450, 350);
}
public static void main(String args[]){
Consultar7 app = new Consultar7();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Consultar8 extends JFrame{
JButton botao;
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3,t4,t5,t6;
String result;
int num;
public Consultar8(){
super("Consulta de Registro");
Container tela = getContentPane();
tela.setLayout(null);
l1 = new JLabel("Código: "); t1 = new JTextField(5);
l2 = new JLabel("Nome: "); t2 = new JTextField(50);
l3 = new JLabel("Idade: "); t3 = new JTextField(2);
l4 = new JLabel("Data Nasc.: "); t4 = new JTextField(10);
l5 = new JLabel("Salário: "); t5 = new JTextField(15);
l6 = new JLabel("Deficiência: "); t6 = new JTextField(5);
l1.setBounds(20,30,80,20); t1.setBounds(100,30,150,20);
l2.setBounds(20,70,80,20); t2.setBounds(100,70,300,20);
l3.setBounds(20,110,80,20);t3.setBounds(100,110,30,20);
l4.setBounds(20,150,80,20);t4.setBounds(100,150,100,20);
l5.setBounds(20,190,80,20);t5.setBounds(100,190,70,20);
l6.setBounds(20,230,80,20);t6.setBounds(100,230,70,20);
botao = new JButton("Consultar Registro"); botao.setBounds(110,270,150,20);
tela.add(l1);tela.add(t1);
tela.add(l2);tela.add(t2);
tela.add(l3);tela.add(t3);
tela.add(l4);tela.add(t4);
tela.add(l5);tela.add(t5);
tela.add(l6);tela.add(t6);
tela.add(botao);
botao.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 5 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Tabela1 WHERE
Cod="+t1.getText());
rs.next();
t2.setText(rs.getString("Nome"));
t3.setText(rs.getString("Idade"));
t4.setText(rs.getString("Dn"));
t5.setText(rs.getString("Sal"));
num=Integer.parseInt(rs.getString("Def"));
if (num==1)
result = "Sim";
else if (num==0)
result = "Não";
t6.setText(result);
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \nPessoa
não encontrada","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
}});
setSize(450, 350);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
Consultar8 app = new Consultar8();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
public class CorDeFundo extends JFrame{
public CorDeFundo(){
super("Definindo a cor de fundo para a janela");
Container tela = getContentPane();
tela.setBackground(Color.blue);
setSize(500, 500);
setVisible(true);
}
public static void main(String args[]){
CorDeFundo app = new CorDeFundo();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
public class CorDeFundo2 extends JFrame{
public CorDeFundo2(){
super("Definindo a cor de fundo para a janela");
Container tela = getContentPane();
tela.setBackground(new Color(255,128,128));
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 5 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
setSize(500, 500);
setVisible(true);
}
public static void main(String args[]){
CorDeFundo2 app = new CorDeFundo2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.DecimalFormat;
public class Data extends JFrame{
JLabel rotulo,rotulo2;
int ds,dia,mes,ano;
Calendar data;
String diasemana[]={"Domingo","Segunda - Feira","Terça - Feira","Quarta - Feira",
"Quinta - Feira","Sexta - Feira","Sábado"};
String meses[]={"Janeiro","Fevereiro","Março","Abril","Maio","Junho",
"Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"};
public Data(){
super("Exemplo de Data");
Container tela = getContentPane();
tela.setLayout(null);
rotulo = new JLabel("");
rotulo2 = new JLabel("");
rotulo.setBounds(20,30,280,20);
rotulo2.setBounds(20,60,280,20);
data = Calendar.getInstance();
ds = data.get(Calendar.DAY_OF_WEEK);
dia = data.get(Calendar.DAY_OF_MONTH);
mes = data.get(Calendar.MONTH);
ano = data.get(Calendar.YEAR);
rotulo.setText("Data: "+ds+" "+dia+"/"+(mes+1)+"/"+ano);
rotulo2.setText("Data: "+diasemana[ds-1]+", "+dia+" de "+meses[mes]+" de "+ano);
tela.add(rotulo);
tela.add(rotulo2);
setSize(300, 200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
Data app = new Data();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
public class DefinirIcone extends JFrame{
public DefinirIcone(){
super("Como definir o ícone para a janela");
ImageIcon icone = new ImageIcon("teste.gif");
setIconImage(icone.getImage());
setSize(300, 150);
setVisible(true);
}
public static void main(String args[]){
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 5 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DesabilitarHabilitar extends JFrame{
JLabel rotulo1, rotulo2;
JButton desabilitar,habilitar;
public DesabilitarHabilitar(){
super("Exemplo de Desabilitar e Habilitar componentes");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel("Rótulo 1");
rotulo2 = new JLabel("Rótulo 2");
desabilitar = new JButton("Desabilitar");
habilitar = new JButton("Habilitar");
rotulo1.setBounds(50,20,100,20);
rotulo2.setBounds(50,60,100,20);
desabilitar.setBounds(80,100,100,20);
habilitar.setBounds(250,100,100,20);
desabilitar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo1.setEnabled(false);
rotulo2.setEnabled(false);
}
}
);
habilitar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo1.setEnabled(true);
rotulo2.setEnabled(true);
}
}
);
tela.add(rotulo1); tela.add(rotulo2);
tela.add(desabilitar); tela.add(habilitar);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
DesabilitarHabilitar app = new DesabilitarHabilitar();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Excluir extends JFrame{
JButton botao;
public Excluir(){
super("Exclusão de Registro");
Container tela = getContentPane();
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 5 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
tela.setLayout(null);
botao = new JButton("Excluir Registro"); botao.setBounds(30,50,150,20);
tela.add(botao);
botao.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
st.executeUpdate("DELETE * FROM Tabela2");
JOptionPane.showMessageDialog(null,"Registros Excluidos Com
Sucesso","Mensagem do Programa",JOptionPane.INFORMATION_MESSAGE);
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \n
Comandos Digitados Inválidos","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
}});
setSize(200, 150);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
Excluir app = new Excluir();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Excluir2 extends JFrame{
JButton botao, botao2;
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3,t4,t5,t6;
String result;
int num;
public Excluir2(){
super("Exclusão de Registro");
Container tela = getContentPane();
tela.setLayout(null);
l1 = new JLabel("Código: "); t1 = new JTextField(5);
l2 = new JLabel("Nome: "); t2 = new JTextField(50);
l3 = new JLabel("Idade: "); t3 = new JTextField(2);
l4 = new JLabel("Data Nasc.: "); t4 = new JTextField(10);
l5 = new JLabel("Salário: "); t5 = new JTextField(15);
l6 = new JLabel("Deficiência: "); t6 = new JTextField(5);
l1.setBounds(20,30,80,20); t1.setBounds(100,30,150,20);
l2.setBounds(20,70,80,20); t2.setBounds(100,70,300,20);
l3.setBounds(20,110,80,20);t3.setBounds(100,110,30,20);
l4.setBounds(20,150,80,20);t4.setBounds(100,150,100,20);
l5.setBounds(20,190,80,20);t5.setBounds(100,190,70,20);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 5 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
l6.setBounds(20,230,80,20);t6.setBounds(100,230,70,20);
botao = new JButton("Consultar Registro"); botao.setBounds(20,270,150,20);
botao2 = new JButton("Excluir Registro"); botao2.setBounds(200,270,150,20);
tela.add(l1);tela.add(t1);
tela.add(l2);tela.add(t2);
tela.add(l3);tela.add(t3);
tela.add(l4);tela.add(t4);
tela.add(l5);tela.add(t5);
tela.add(l6);tela.add(t6);
tela.add(botao);tela.add(botao2);
botao.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Tabela2 WHERE
Cod="+t1.getText());
rs.next();
t2.setText(rs.getString("Nome"));
t3.setText(rs.getString("Idade"));
t4.setText(rs.getString("Dn"));
t5.setText(rs.getString("Sal"));
num=Integer.parseInt(rs.getString("Def"));
if (num==1)
result = "Sim";
else if (num==0)
result = "Não";
t6.setText(result);
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \nPessoa
não encontrada","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
}});
botao2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
st.executeUpdate("DELETE FROM Tabela2 WHERE Cod="+t1.getText());
JOptionPane.showMessageDialog(null,"Registro Excluido com Sucesso","Mensagem
do Programa",JOptionPane.INFORMATION_MESSAGE);
t1.setText(""); t2.setText(""); t3.setText(""); t4.setText(""); t5.setText("");t6.setText("");
t1.requestFocus();
st.close();
con.close();
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 5 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \nPessoa
não encontrada","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
}});
setSize(450, 350);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
Excluir2 app = new Excluir2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBarraDeFerramentas extends JFrame{
JToolBar barra;
JButton direita,esquerda,centralizar,recortar,copiar,colar;
ImageIcon imagens[];
public ExemploBarraDeFerramentas(){
super("Exemplo de Barra de Ferramentas");
Container tela = getContentPane();
tela.setLayout(null);
String icones[]={"imagens/direita.gif","imagens/esquerda.gif",
"imagens/centro.gif","imagens/recortar.gif",
"imagens/copiar.gif","imagens/colar.gif"};
imagens = new ImageIcon[6];
for(int i = 0;i < 6;i++){
imagens[i] = new ImageIcon(icones[i]);
}
direita = new JButton(imagens[0]);
esquerda = new JButton(imagens[1]);
centralizar = new JButton(imagens[2]);
recortar = new JButton(imagens[3]);
copiar = new JButton(imagens[4]);
colar = new JButton(imagens[5]);
direita.setToolTipText("Direita (Ctrl+d)");
esquerda.setToolTipText("Esquerda (Ctrl+e)");
centralizar.setToolTipText("Centralizar (Ctrl+z)");
recortar.setToolTipText("Recortar (Ctrl+x)");
copiar.setToolTipText("Copiar (Ctrl+c)");
colar.setToolTipText("Colar (Ctrl+v)");
barra = new JToolBar("Barra de Ferramentas");
UIManager.put("ToolTip.background",SystemColor.info);
UIManager.put("ToolTip.foreground",Color.blue);
barra.setRollover(true);
barra.add(direita);
barra.add(esquerda);
barra.add(centralizar);
barra.addSeparator();
barra.add(recortar);
barra.add(copiar);
barra.add(colar);
barra.setBounds(1,1,260,50);
tela.add(barra);
setSize(320,340);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 5 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploBarraDeFerramentas app = new ExemploBarraDeFerramentas();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotao extends JFrame{
JButton botao1,botao2,botao3,botao4;
public ExemploBotao(){
super("Exemplo com JButton");
Container tela = getContentPane();
setLayout(null);
botao1 = new JButton ("Procurar");
botao2 = new JButton ("Voltar >>");
botao3 = new JButton ("Próximo >>");
botao4 = new JButton ("Abrir");
botao1.setBounds(50,20,100,20);
botao2.setBounds(50,60,100,20);
botao3.setBounds(50,100,100,20);
botao4.setBounds(50,140,100,20);
tela.add(botao1);
tela.add(botao2);
tela.add(botao3);
tela.add(botao4);
setSize(400, 250);
setVisible(true);
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotaoAoPressionarEnter extends JFrame{
JButton botao1,botao2,botao3,botao4;
public ExemploBotaoAoPressionarEnter(){
super("Exemplo com JButton");
Container tela = getContentPane();
setLayout(null);
botao1 = new JButton ("Procurar");
botao2 = new JButton ("Voltar >>");
botao3 = new JButton ("Próximo >>");
botao4 = new JButton ("Abrir");
botao1.setBounds(50,20,100,20);
botao2.setBounds(50,60,100,20);
botao3.setBounds(50,100,100,20);
botao4.setBounds(50,140,100,20);
getRootPane().setDefaultButton(botao4);
tela.add(botao1);
tela.add(botao2);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 5 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
tela.add(botao3);
tela.add(botao4);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploBotaoAoPressionarEnter app = new ExemploBotaoAoPressionarEnter();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotaocomBotaoAtalho extends JFrame{
JButton botao1,botao2,botao3,botao4;
public ExemploBotaocomBotaoAtalho(){
super("Exemplo com JButton");
Container tela = getContentPane();
setLayout(null);
botao1 = new JButton ("Procurar");
botao2 = new JButton ("Voltar >>");
botao3 = new JButton ("Próximo >>");
botao4 = new JButton ("Abrir");
botao1.setBounds(50,20,100,20);
botao2.setBounds(50,60,100,20);
botao3.setBounds(50,100,100,20);
botao4.setBounds(50,140,100,20);
botao1.setMnemonic(KeyEvent.VK_P);
botao2.setMnemonic(KeyEvent.VK_V);
botao3.setMnemonic(KeyEvent.VK_X);
botao4.setMnemonic(KeyEvent.VK_S);
tela.add(botao1);
tela.add(botao2);
tela.add(botao3);
tela.add(botao4);
setSize(400, 250);
setVisible(true);
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotaoCordaLetra extends JFrame{
JButton botao1,botao2,botao3,botao4;
public ExemploBotaoCordaLetra(){
super("Exemplo com JButton");
Container tela = getContentPane();
setLayout(null);
botao1 = new JButton ("Procurar");
botao2 = new JButton ("Voltar >>");
botao3 = new JButton ("Próximo >>");
botao4 = new JButton ("Abrir");
botao1.setBounds(50,20,100,20);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 5 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
botao2.setBounds(50,60,100,20);
botao3.setBounds(50,100,100,20);
botao4.setBounds(50,140,100,20);
botao1.setForeground(Color.blue);
botao2.setForeground(Color.green);
botao3.setForeground(Color.red);
botao4.setForeground(Color.pink);
tela.add(botao1);
tela.add(botao2);
tela.add(botao3);
tela.add(botao4);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploBotaoCordaLetra app = new ExemploBotaoCordaLetra();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotaoCordeFundo extends JFrame{
JButton botao1,botao2,botao3,botao4;
public ExemploBotaoCordeFundo(){
super("Exemplo com JButton");
Container tela = getContentPane();
setLayout(null);
botao1 = new JButton ("Procurar");
botao2 = new JButton ("Voltar >>");
botao3 = new JButton ("Próximo >>");
botao4 = new JButton ("Abrir");
botao1.setBounds(50,20,100,20);
botao2.setBounds(50,60,100,20);
botao3.setBounds(50,100,100,20);
botao4.setBounds(50,140,100,20);
botao1.setBackground(Color.yellow);
botao2.setBackground(Color.red);
botao3.setBackground(Color.blue);
botao4.setBackground(Color.white);
tela.add(botao1);
tela.add(botao2);
tela.add(botao3);
tela.add(botao4);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploBotaoCordeFundo app = new ExemploBotaoCordeFundo();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotaoCordeFundo extends JFrame{
JButton botao1,botao2,botao3,botao4;
public ExemploBotaoCordeFundo(){
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 6 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotaoSair1 extends JFrame{
JButton botao;
public ExemploBotaoSair1(){
super("Exemplo de Botões com Dica");
Container tela = getContentPane();
tela.setLayout(null);
botao = new JButton("Sair");
botao.setBounds(100,50,100,20);
botao.setToolTipText("Exemplo de Botões com Diálogos de confirmação");
tela.add(botao);
botao.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
int opcao;
opcao = JOptionPane.showConfirmDialog(null,"Deseja mesmo
fechar a janela?","Fechar",JOptionPane.YES_NO_OPTION);
if (opcao==JOptionPane.YES_OPTION)
System.exit(0);
}});
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploBotaoSair1 app = new ExemploBotaoSair1();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 6 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotaoSair extends JFrame{
JButton botaosair;
public ExemploBotaoSair(){
super("Exemplo com JButton");
Container tela = getContentPane();
setLayout(null);
botaosair = new JButton ("Sair");
botaosair.setBounds(100,50,100,20);
botaosair.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
} } );
tela.add(botaosair);
setSize(300, 150);
setVisible(true);
}
public static void main(String args[]){
ExemploBotaoSair app = new ExemploBotaoSair();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotoes extends JFrame{
JButton botaotexto,botaoimagemtexto,botaoimagem;
ImageIcon icone;
public ExemploBotoes(){
super("Exemplo com JButton");
Container tela = getContentPane();
setLayout(null);
icone = new ImageIcon("abrir.gif");
botaotexto = new JButton ("Novo");
botaoimagemtexto = new JButton ("Abrir",icone);
botaoimagem = new JButton (icone);
botaotexto.setBounds(50,20,100,20);
botaoimagemtexto.setBounds(50,60,100,20);
botaoimagem.setBounds(50,100,100,20);
tela.add(botaotexto);
tela.add(botaoimagemtexto);
tela.add(botaoimagem);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploBotoes app = new ExemploBotoes();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotoesDicas extends JFrame{
JButton botao1,botao2;
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 6 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
public ExemploBotoesDicas(){
super("Exemplo de Botões com Dica");
Container tela = getContentPane();
tela.setLayout(null);
botao1 = new JButton("Abrir");
botao2 = new JButton("Sair");
botao1.setBounds(100,50,100,20);
botao2.setBounds(100,100,100,20);
botao1.setToolTipText("Botão usado para abrir algo");
botao2.setToolTipText("Botão que será usado para sair");
tela.add(botao1);
tela.add(botao2);
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploBotoesDicas app = new ExemploBotoesDicas();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploBotoesDicas2 extends JFrame{
JButton botao1,botao2;
public ExemploBotoesDicas2(){
super("Exemplo de Botões com Dica");
Container tela = getContentPane();
tela.setLayout(null);
botao1 = new JButton("Abrir");
botao2 = new JButton("Sair");
botao1.setBounds(100,50,100,20);
botao2.setBounds(100,100,100,20);
botao1.setToolTipText("Botão usado para abrir algo");
botao2.setToolTipText("Botão que será usado para sair");
UIManager.put("ToolTip.background",SystemColor.info);
UIManager.put("ToolTip.foreground",Color.blue);
tela.add(botao1);
tela.add(botao2);
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploBotoesDicas2 app = new ExemploBotoesDicas2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploComboCheckRadio extends JFrame{
JLabel rotulo1, rotulo2, rotulo3,texto;
JCheckBox negrito,italico,normal,negritoitalico;
JRadioButton tam1,tam2,tam3,tam4;
ButtonGroup grupo;
String cor[] = {"Sem Cor","Vermelho","Azul","Verde","Amarelo","Branco","Preto"};
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 6 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
JComboBox lista;
Integer estilo, tamfonte;
public ExemploComboCheckRadio(){
super("Exemplo Combo Check Radio BOX");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel("Cor");
rotulo2 = new JLabel("Estilo");
rotulo3 = new JLabel("Tamanho");
texto = new JLabel("Programa feito em Java");
lista = new JComboBox(cor);
lista.setMaximumRowCount(7);
negrito = new JCheckBox("Negrito") ;
italico = new JCheckBox("Italico");
normal = new JCheckBox("Normal");
negritoitalico = new JCheckBox("Negrito Itálico");
tam1 = new JRadioButton("12");
tam2 = new JRadioButton("14");
tam3 = new JRadioButton("16");
tam4 = new JRadioButton("18");
grupo = new ButtonGroup();
grupo.add(tam1);
grupo.add(tam2);
grupo.add(tam3);
grupo.add(tam4);
rotulo1.setBounds(40,20,70,20);
rotulo2.setBounds(200,20,70,20);
rotulo3.setBounds(300,20,70,20);
texto.setBounds(100,200,300,20);
lista.setBounds(40,50,150,20);
negrito.setBounds(200,50,100,20);
italico.setBounds(200,70,100,20);
normal.setBounds(200,90,100,20);
negritoitalico.setBounds(200,110,150,20);
tam1.setBounds(350,50,100,20);
tam2.setBounds(350,70,100,20);
tam3.setBounds(350,90,100,20);
tam4.setBounds(350,110,100,20);
tamfonte=12;
estilo=Font.PLAIN;
lista.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (lista.getSelectedItem().toString() == "Sem Cor")
texto.setForeground(Color.black);
if (lista.getSelectedItem().toString() == "Vermelho")
texto.setForeground(Color.red);
if (lista.getSelectedItem().toString() == "Azul")
texto.setForeground(Color.blue);
if (lista.getSelectedItem().toString() == "Verde")
texto.setForeground(Color.green);
if (lista.getSelectedItem().toString() == "Amarelo")
texto.setForeground(Color.yellow);
if (lista.getSelectedItem().toString() == "Branco")
texto.setForeground(Color.white);
if (lista.getSelectedItem().toString() == "Preto")
texto.setForeground(Color.black);}});
//coloca a fonte tamnho 12
tam1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tamfonte=12;
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 6 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte tamnho 14
tam2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tamfonte=14;
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte tamnho 16
tam3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tamfonte=16;
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte tamnho 18
tam4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tamfonte=18;
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte em negrito
negrito.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
estilo=Font.BOLD;
normal.setSelected(false);
italico.setSelected(false);
negritoitalico.setSelected(false);
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte em italico
italico.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
estilo=Font.ITALIC;
normal.setSelected(false);
negrito.setSelected(false);
negritoitalico.setSelected(false);
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte normal
normal.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
estilo=Font.PLAIN;
negrito.setSelected(false);
italico.setSelected(false);
negritoitalico.setSelected(false);
texto.setFont(new Font("",estilo,tamfonte));}});
//coloca a fonte em negrito e italico
negritoitalico.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
estilo=Font.BOLD+Font.ITALIC;
negrito.setSelected(false);
italico.setSelected(false);
normal.setSelected(false);
texto.setFont(new Font("",estilo,tamfonte));}});
tela.add(rotulo1);
tela.add(rotulo2);
tela.add(rotulo3);
tela.add(texto);
tela.add(negrito);
tela.add(italico);
tela.add(normal);
tela.add(negritoitalico);
tela.add(tam1);
tela.add(tam2);
tela.add(tam3);
tela.add(tam4);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 6 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
tela.add(lista);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]){
ExemploComboCheckRadio app = new ExemploComboCheckRadio();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMenu extends JFrame{
JMenuBar barra;
JMenu opcoes;
JMenuItem limpar,fonte,sair;
public ExemploDeMenu(){
super("Exemplo de Menus");
Container tela = getContentPane();
tela.setLayout(null);
barra = new JMenuBar();
setJMenuBar(barra);
opcoes = new JMenu("Opções");
barra.add(opcoes);
limpar = new JMenuItem("Limpar");
fonte = new JMenuItem("Fonte");
sair = new JMenuItem("Sair");
limpar.setMnemonic(KeyEvent.VK_L);
fonte.setMnemonic(KeyEvent.VK_F);
sair.setMnemonic(KeyEvent.VK_S);
opcoes.add(limpar);
opcoes.add(fonte);
opcoes.addSeparator();
opcoes.add(sair);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploDeMenu app = new ExemploDeMenu();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMenu2 extends JFrame{
JMenuBar barra;
JMenu opcoes,fonte,cor;
JMenuItem limpar,sair,estilo,tamanho,azul,verde,vermelho,amarelo,preto;
public ExemploDeMenu2(){
super("Exemplo de Menus com submenus");
Container tela = getContentPane();
tela.setLayout(null);
barra = new JMenuBar();
setJMenuBar(barra);
opcoes = new JMenu("Opções");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 6 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
barra.add(opcoes);
limpar = new JMenuItem("Limpar");
fonte = new JMenu("Fonte");
cor = new JMenu("Cor");
azul = new JMenuItem("Azul");
verde = new JMenuItem("Verde");
vermelho = new JMenuItem("Vermelho");
amarelo = new JMenuItem("Amarelo");
preto = new JMenuItem("Preto");
estilo = new JMenuItem("Estilo");
tamanho = new JMenuItem("Tamanho");
sair = new JMenuItem("Sair");
limpar.setMnemonic(KeyEvent.VK_L);
fonte.setMnemonic(KeyEvent.VK_F);
sair.setMnemonic(KeyEvent.VK_S);
cor.setMnemonic(KeyEvent.VK_C);
estilo.setMnemonic(KeyEvent.VK_E);
tamanho.setMnemonic(KeyEvent.VK_T);
opcoes.add(limpar);
opcoes.add(fonte);
opcoes.addSeparator();
opcoes.add(sair);
fonte.add(cor);
fonte.add(estilo);
fonte.add(tamanho);
cor.add(azul);
cor.add(verde);
cor.add(vermelho);
cor.add(amarelo);
cor.add(preto);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploDeMenu2 app = new ExemploDeMenu2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMenu3 extends JFrame{
JMenuBar barra;
JMenu opcoes,fonte,estilo,cor;
JMenuItem limpar,sair,tamanho,azul,verde,vermelho,amarelo,preto;
JCheckBoxMenuItem normal, negrito, italico, negritoitalico;
public ExemploDeMenu3(){
super("Exemplo de Menus com JChekBoxMenuItem");
Container tela = getContentPane();
tela.setLayout(null);
barra = new JMenuBar();
setJMenuBar(barra);
opcoes = new JMenu("Opções");
barra.add(opcoes);
limpar = new JMenuItem("Limpar");
fonte = new JMenu("Fonte");
cor = new JMenu("Cor");
azul = new JMenuItem("Azul");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 6 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMenu4 extends JFrame{
JMenuBar barra;
JMenu opcoes,fonte,cor,estilo,tamanho;
JMenuItem limpar,sair,azul,verde,vermelho,amarelo,preto;
JCheckBoxMenuItem nomeE[];
ButtonGroup grupoT,grupoE;
JRadioButtonMenuItem tamanhoF[];
String tam[] = {"12","14","16","18"};
String est[] = {"Normal", "Negrito", "Itálico", "Negrito e Itálico"};
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 6 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
public ExemploDeMenu4(){
super("Exemplo de Menus com JRadioButtonMenuItem");
Container tela = getContentPane();
tela.setLayout(null);
barra = new JMenuBar();
setJMenuBar(barra);
opcoes = new JMenu("Opções");
barra.add(opcoes);
limpar = new JMenuItem("Limpar");
fonte = new JMenu("Fonte");
cor = new JMenu("Cor");
azul = new JMenuItem("Azul");
verde = new JMenuItem("Verde");
vermelho = new JMenuItem("Vermelho");
amarelo = new JMenuItem("Amarelo");
preto = new JMenuItem("Preto");
estilo = new JMenu("Estilo");
grupoE = new ButtonGroup();
nomeE = new JCheckBoxMenuItem[4];
for(int i = 0; i < 4; i++){
nomeE[i] = new JCheckBoxMenuItem(est[i]);
estilo.add(nomeE[i]);
grupoE.add(nomeE[i]);
}
tamanho = new JMenu("Tamanho");
grupoT = new ButtonGroup();
tamanhoF = new JRadioButtonMenuItem[4];
for(int i = 0; i < 4; i++){
tamanhoF[i] = new JRadioButtonMenuItem(tam[i]);
tamanho.add(tamanhoF[i]);
grupoT.add(tamanhoF[i]);
}
sair = new JMenuItem("Sair");
opcoes.setMnemonic(KeyEvent.VK_O);
limpar.setMnemonic(KeyEvent.VK_L);
fonte.setMnemonic(KeyEvent.VK_F);
sair.setMnemonic(KeyEvent.VK_S);
cor.setMnemonic(KeyEvent.VK_C);
estilo.setMnemonic(KeyEvent.VK_E);
tamanho.setMnemonic(KeyEvent.VK_T);
opcoes.add(limpar);
opcoes.add(fonte);
opcoes.addSeparator();
opcoes.add(sair);
cor.add(azul);
cor.add(verde);
cor.add(vermelho);
cor.add(amarelo);
cor.add(preto);
fonte.add(cor);
fonte.add(estilo);
fonte.add(tamanho);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploDeMenu4 app = new ExemploDeMenu4();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 6 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMenu5 extends JFrame{
JMenuBar barra;
JMenu opcoes,fonte,cor,estilo,tamanho;
JMenuItem limpar,sair,azul,verde,vermelho,amarelo,preto;
JCheckBoxMenuItem nomeE[];
ButtonGroup grupoT,grupoE;
JRadioButtonMenuItem tamanhoF[];
String tam[] = {"12","14","16","18"};
String est[] = {"Normal", "Negrito", "Itálico", "Negrito e Itálico"};
JTextArea texto;
JPanel painel;
JScrollPane rolagem;
int estilofonte, tamfonte;
public ExemploDeMenu5(){
super("Exemplo de Menus executando ações");
Container tela = getContentPane();
tela.setLayout(null);
estilofonte=Font.PLAIN;
tamfonte=12;
barra = new JMenuBar();
setJMenuBar(barra);
opcoes = new JMenu("Opções");
barra.add(opcoes);
limpar = new JMenuItem("Limpar");
fonte = new JMenu("Fonte");
cor = new JMenu("Cor");
azul = new JMenuItem("Azul");
verde = new JMenuItem("Verde");
vermelho = new JMenuItem("Vermelho");
amarelo = new JMenuItem("Amarelo");
preto = new JMenuItem("Preto");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 7 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
fonte.setMnemonic(KeyEvent.VK_F);
sair.setMnemonic(KeyEvent.VK_S);
cor.setMnemonic(KeyEvent.VK_C);
estilo.setMnemonic(KeyEvent.VK_E);
tamanho.setMnemonic(KeyEvent.VK_T);
opcoes.add(limpar);
opcoes.add(fonte);
opcoes.addSeparator();
opcoes.add(sair);
cor.add(azul);
cor.add(verde);
cor.add(vermelho);
cor.add(amarelo);
cor.add(preto);
fonte.add(cor);
fonte.add(estilo);
fonte.add(tamanho);
texto = new JTextArea(10,20);
rolagem = new JScrollPane(texto);
rolagem.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
rolagem.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWA
YS);
painel = new JPanel();
painel.add(rolagem);
painel.setBounds(30,30,250,250);
tela.add(painel);
limpar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto.setText("");
texto.requestFocus();}});
azul.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto.setForeground(Color.blue);
repaint();}});
verde.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto.setForeground(Color.green);
repaint();}});
vermelho.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto.setForeground(Color.red);
repaint();}});
amarelo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto.setForeground(Color.yellow);
repaint();}});
preto.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto.setForeground(Color.black);
repaint();}});
sair.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int resposta;
resposta=JOptionPane.showConfirmDialog(null,"Deseja realmente
sair?","Mensagem do Programa",JOptionPane.YES_NO_OPTION);
if (resposta==6)
System.exit(0);}});
setSize(500,300);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 7 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploDeMenu5 app = new ExemploDeMenu5();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class TratadorE implements ItemListener{
public void itemStateChanged(ItemEvent e){
if(nomeE[0].isSelected())
estilofonte= Font.PLAIN;
if(nomeE[1].isSelected())
estilofonte= Font.BOLD;
if(nomeE[2].isSelected())
estilofonte= Font.ITALIC;
if(nomeE[3].isSelected())
estilofonte= Font.BOLD+Font.ITALIC;
texto.setFont(new Font("", estilofonte, tamfonte));
repaint(); } }
private class TratadorT implements ItemListener{
public void itemStateChanged(ItemEvent e){
if(tamanhoF[0].isSelected())
tamfonte= 12;
if(tamanhoF[1].isSelected())
tamfonte= 14;
if(tamanhoF[2].isSelected())
tamfonte= 16;
if(tamanhoF[3].isSelected())
tamfonte= 18;
texto.setFont(new Font("", estilofonte, tamfonte));
repaint(); } }
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDeMessagens extends JFrame{
JButton erro, informacao, exclamacao, pergunta, nenhum;
public ExemploDeMessagens(){
super("Exemplo de mensagens");
Container tela = getContentPane();
tela.setLayout(null);
erro = new JButton("Erro");
informacao = new JButton("Informação");
exclamacao = new JButton("Exclamação");
pergunta = new JButton("Pergunta");
nenhum = new JButton("Nenhum");
erro.setBounds(30,20,100,20);
informacao.setBounds(30,50,100,20);
exclamacao.setBounds(30,80,150,20);
pergunta.setBounds(30,110,100,20);
nenhum.setBounds(30,140,100,20);
tela.add(erro);
tela.add(informacao);
tela.add(exclamacao);
tela.add(pergunta);
tela.add(nenhum);
erro.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 7 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploDePopupMenu extends JFrame{
JPopupMenu opcoes;
JMenuItem recortar,copiar,colar;
JTextArea texto;
public ExemploDePopupMenu(){
super("Exemplo de PopupMenu");
Container tela = getContentPane();
tela.setLayout(null);
texto = new JTextArea(10,20);
texto.setBounds(30,30,250,250);
texto.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e) {
if(e.isPopupTrigger())
opcoes.show(e.getComponent(),e.getX(),e.getY());
}});
Tratador tratmenu = new Tratador();
opcoes = new JPopupMenu();
recortar = new JMenuItem("Recortar");
copiar = new JMenuItem("Copiar");
colar = new JMenuItem("Colar");
recortar.setMnemonic(KeyEvent.VK_R);
copiar.setMnemonic(KeyEvent.VK_C);
colar.setMnemonic(KeyEvent.VK_L);
recortar.addActionListener(tratmenu);
copiar.addActionListener(tratmenu);
colar.addActionListener(tratmenu);
opcoes.add(recortar);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 7 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
opcoes.add(copiar);
opcoes.addSeparator();
opcoes.add(colar);
tela.add(texto);
setSize(320,340);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploDePopupMenu app = new ExemploDePopupMenu();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class Tratador implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource()==recortar)
texto.cut();
if(e.getSource()==copiar)
texto.copy();
if(e.getSource()==colar)
texto.paste();
repaint();
}}}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploInputDialog extends JFrame{
JButton botao;
String nome;
JLabel rotulo;
public ExemploInputDialog(){
super("Exemplo de Input Dialog");
Container tela = getContentPane();
tela.setLayout(null);
nome = JOptionPane.showInputDialog("Entre com seu nome: ");
rotulo = new JLabel("");
botao = new JButton("Sair");
rotulo.setBounds(10,40,350,20);
botao.setBounds(100,90,100,20);
botao.setToolTipText("Botão que finaliza a janela");
rotulo.setText("O nome digitado foi: "+nome.toUpperCase());
tela.add(rotulo);
tela.add(botao);
botao.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
int opcao;
Object[] botoes = {"Sim","Não"};
opcao = JOptionPane.showOptionDialog(null,"Deseja mesmo
fechar a
janela?","Fechar",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,b
otoes,botoes[0]);
if (opcao==JOptionPane.YES_OPTION)
System.exit(0);
}});
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 7 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.JOptionPane;
public class ExemploInputDialog1{
public static void main(String args[]){
Object linguagens [] = {"Java","Delphi","C++","Visual Basic"};
Object opcao = JOptionPane.showInputDialog(null,"Qual sua linguagem
favorita?","Enquete",JOptionPane.QUESTION_MESSAGE,null,linguagens,linguagens[0]);
JOptionPane.showMessageDialog(null,"Você escolheu: "+opcao);
System.exit(0);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJCheckBox extends JFrame{
JCheckBox primeira,segunda,terceira,quarta,quinta;
JLabel vazio;
public ExemploJCheckBox(){
super("Exemplo de um JCheckBox");
Container tela = getContentPane();
tela.setLayout(null);
JLabel rotulo = new JLabel("Quais suas linguagens favoritas? ");
rotulo.setBounds(40,30,200,20);
primeira = new JCheckBox("Java");
primeira.setMnemonic(KeyEvent.VK_J);
primeira.setBounds(40,60,60,20);
segunda = new JCheckBox("C++");
segunda.setMnemonic(KeyEvent.VK_C);
segunda.setBounds(100,60,60,20);
terceira = new JCheckBox("Delphi");
terceira.setMnemonic(KeyEvent.VK_D);
terceira.setBounds(160,60,60,20);
quarta = new JCheckBox("Visual Basic");
quarta.setMnemonic(KeyEvent.VK_V);
quarta.setBounds(230,60,100,20);
quinta = new JCheckBox("Python");
quinta.setMnemonic(KeyEvent.VK_P);
quinta.setBounds(335,60,70,20);
JButton botao = new JButton("Exibir");
botao.setBounds(200,150,100,20);
vazio = new JLabel("");
vazio.setBounds(100,200,600,20);
botao.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
String escolhas = "";
if (primeira.isSelected() ==true)
escolhas = escolhas + primeira.getText();
if (segunda.isSelected() ==true)
escolhas = escolhas +" "+segunda.getText();
if (terceira.isSelected() ==true)
escolhas = escolhas +" "+terceira.getText();
if (quarta.isSelected() ==true)
escolhas = escolhas +" "+quarta.getText();
if (quinta.isSelected() ==true)
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 7 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJCheckBox1 extends JFrame{
JCheckBox primeira,segunda,terceira,quarta,quinta;
JLabel vazio;
public ExemploJCheckBox1(){
super("Exemplo de um JCheckBox");
Container tela = getContentPane();
tela.setLayout(null);
JLabel rotulo = new JLabel("Quais suas linguagens favoritas? ");
rotulo.setBounds(40,30,200,20);
primeira = new JCheckBox("Java");
primeira.setMnemonic(KeyEvent.VK_J);
primeira.setBounds(40,60,60,20);
primeira.setForeground(Color.blue);
segunda = new JCheckBox("C++");
segunda.setMnemonic(KeyEvent.VK_C);
segunda.setBounds(100,60,60,20);
segunda.setForeground(Color.red);
terceira = new JCheckBox("Delphi");
terceira.setMnemonic(KeyEvent.VK_D);
terceira.setBounds(160,60,60,20);
terceira.setForeground(Color.green);
quarta = new JCheckBox("Visual Basic");
quarta.setMnemonic(KeyEvent.VK_V);
quarta.setBounds(230,60,100,20);
quarta.setForeground(Color.yellow);
quinta = new JCheckBox("Python");
quinta.setMnemonic(KeyEvent.VK_P);
quinta.setBounds(335,60,70,20);
quinta.setForeground(Color.white);
JButton botao = new JButton("Exibir");
botao.setBounds(200,150,100,20);
vazio = new JLabel("");
vazio.setBounds(100,200,600,20);
botao.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
String escolhas = "";
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 7 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
if (primeira.isSelected() ==true)
escolhas = escolhas + primeira.getText();
if (segunda.isSelected() ==true)
escolhas = escolhas +" "+segunda.getText();
if (terceira.isSelected() ==true)
escolhas = escolhas +" "+terceira.getText();
if (quarta.isSelected() ==true)
escolhas = escolhas +" "+quarta.getText();
if (quinta.isSelected() ==true)
escolhas = escolhas+" "+quinta.getText();
vazio.setText("Você escolheu: "+escolhas);}});
tela.add(rotulo);
tela.add(primeira);
tela.add(segunda);
tela.add(terceira);
tela.add(quarta);
tela.add(quinta);
tela.add(botao);
tela.add(vazio);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploJCheckBox1 app = new ExemploJCheckBox1();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJCheckBox2 extends JFrame{
JCheckBox primeira,segunda,terceira,quarta,quinta;
public ExemploJCheckBox2(){
super("Exemplo de um JCheckBox");
Container tela = getContentPane();
tela.setLayout(null);
primeira.setMnemonic(KeyEvent.VK_J);
segunda.setMnemonic(KeyEvent.VK_C);
terceira.setMnemonic(KeyEvent.VK_D);
quarta.setMnemonic(KeyEvent.VK_V);
quinta.setMnemonic(KeyEvent.VK_P);
primeira.setBounds(40,60,60,20);
segunda.setBounds(100,60,60,20);
terceira.setBounds(160,60,60,20);
quarta.setBounds(230,60,100,20);
quinta.setBounds(335,60,70,20);
primeira.setSelected(true);
tela.add(primeira);
tela.add(segunda);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 7 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
tela.add(terceira);
tela.add(quarta);
tela.add(quinta);
setSize(500,300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main (String args[]){
ExemploJCheckBox2 app = new ExemploJCheckBox2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJComboBox extends JFrame{
JComboBox lista;
String cidades[] = {"Rio de Janeiro","São Paulo","Minas Gerais","Espírito Santo",
"Bahia","Pernambuco","Rio Grande do Sul","Acre"};
JButton exibir;
JLabel rotulo;
public ExemploJComboBox(){
super("Exemplo de JComboBox");
Container tela = getContentPane();
setLayout(null);
exibir = new JButton("Exibir");
rotulo = new JLabel("");
lista = new JComboBox(cidades);
lista.setMaximumRowCount(5);
lista.setBounds(50,50,150,30);
exibir.setBounds(270,50,100,30);
rotulo.setBounds(50,150,200,30);
exibir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo.setText("o estado é: "+lista.getSelectedItem().toString());
}
}
);
tela.add(lista);
tela.add(exibir);
tela.add(rotulo);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploJComboBox app = new ExemploJComboBox();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJComboBox2 extends JFrame{
JComboBox lista;
String cidades[] = {"Rio de Janeiro","São Paulo","Minas Gerais","Espírito Santo",
"Bahia","Pernambuco","Rio Grande do Sul","Acre"};
JButton exibir;
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 7 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
JLabel rotulo;
public ExemploJComboBox2(){
super("Exemplo de JComboBox");
Container tela = getContentPane();
setLayout(null);
exibir = new JButton("Exibir");
rotulo = new JLabel("");
lista = new JComboBox(cidades);
lista.setEditable(true);
lista.setMaximumRowCount(5);
lista.setBounds(50,50,150,30);
exibir.setBounds(270,50,100,30);
rotulo.setBounds(50,150,200,30);
exibir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo.setText("o estado é: "+lista.getSelectedItem().toString());
}
}
);
tela.add(lista);
tela.add(exibir);
tela.add(rotulo);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploJComboBox2 app = new ExemploJComboBox2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
public class ExemploJFormattedTextField extends JFrame{
JLabel rotulocep,rotulotel,rotulocpf,rotulodata;
JFormattedTextField cep,tel, cpf, data;
MaskFormatter mascaracep,mascaratel, mascaracpf, mascaradata;
public ExemploJFormattedTextField(){
super("Exemplo com JFormattedTextField");
Container tela = getContentPane();
setLayout(null);
rotulocep = new JLabel("CEP: ");
rotulotel = new JLabel("Telefone: ");
rotulocpf = new JLabel("CPF: ");
rotulodata = new JLabel("Data: ");
rotulocep.setBounds(50,40,100,20);
rotulotel.setBounds(50,80,100,20);
rotulocpf.setBounds(50,120,100,20);
rotulodata.setBounds(50,160,100,20);
try{
mascaracep = new MaskFormatter("#####-###");
mascaratel = new MaskFormatter("(##)####-####");
mascaracpf = new MaskFormatter("#########-##");
mascaradata = new MaskFormatter("##/##/####");
mascaracep.setPlaceholderCharacter('_');
mascaratel.setPlaceholderCharacter('_');
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 7 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
mascaracpf.setPlaceholderCharacter('_');
mascaradata.setPlaceholderCharacter('_');
}
catch(ParseException excp){}
cep = new JFormattedTextField(mascaracep);
tel = new JFormattedTextField(mascaratel);
cpf = new JFormattedTextField(mascaracpf);
data = new JFormattedTextField(mascaradata);
cep.setBounds(150,40,150,20);
tel.setBounds(150,80,150,20);
cpf.setBounds(150,120,150,20);
data.setBounds(150,160,150,20);
cep.setForeground(Color.blue);
tel.setForeground(Color.red);
cpf.setForeground(Color.green);
data.setForeground(new Color(255,128,128));
cep.setBackground(Color.yellow);
tel.setBackground(Color.yellow);
cpf.setBackground(new Color(255,255,204));
data.setBackground(new Color(255,255,204));
cep.setFont(new Font("Times New Roman",Font.BOLD,14));
tel.setFont(new Font("Comic Sans MS",Font.PLAIN,14));
cpf.setFont(new Font("Arial",Font.BOLD,14));
data.setFont(new Font("Tahoma",Font.BOLD,14));
tela.add(rotulocep);
tela.add(rotulotel);
tela.add(rotulocpf);
tela.add(rotulodata);
tela.add(cep);
tela.add(tel);
tela.add(cpf);
tela.add(data);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploJFormattedTextField app = new ExemploJFormattedTextField();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJList extends JFrame{
JList lista;
String cidades[] = {"Rio de Janeiro","São Paulo","Minas Gerais","Espírito Santo",
"Bahia","Pernambuco","Rio Grande do Sul","Acre"};
JButton exibir;
JLabel rotulo;
public ExemploJList(){
super("Exemplo de List");
Container tela = getContentPane();
setLayout(null);
exibir = new JButton("Exibir");
rotulo = new JLabel("");
lista = new JList(cidades);
lista.setVisibleRowCount(5);
JScrollPane painelRolagem = new JScrollPane(lista);
lista.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 8 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
painelRolagem.setBounds(40,50,150,100);
exibir.setBounds(270,50,100,30);
rotulo.setBounds(50,150,200,30);
exibir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo.setText("o estado é: "+lista.getSelectedValue().toString());
}
}
);
tela.add(painelRolagem);
tela.add(exibir);
tela.add(rotulo);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploJList app = new ExemploJList();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJList2 extends JFrame{
JList lista;
String cidades[] = {"Rio de Janeiro","São Paulo","Minas Gerais","Espírito Santo",
"Bahia","Pernambuco","Rio Grande do Sul","Acre"};
JButton exibir;
public ExemploJList2(){
super("Exemplo de List");
Container tela = getContentPane();
setLayout(null);
exibir = new JButton("Exibir");
lista = new JList(cidades);
lista.setVisibleRowCount(5);
JScrollPane painelRolagem = new JScrollPane(lista);
lista.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
painelRolagem.setBounds(40,50,150,100);
exibir.setBounds(270,50,100,30);
exibir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
Object selecionados[] = lista.getSelectedValues();
String resultados = "Valores selecionados:\n";
for(int i=0;i<selecionados.length;i++)
resultados += selecionados[i].toString()+"\n";
JOptionPane.showMessageDialog(null,resultados);
}
}
);
tela.add(painelRolagem);
tela.add(exibir);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploJList2 app = new ExemploJList2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 8 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJList3 extends JFrame{
JList lista;
String cidades[] = {"Rio de Janeiro","São Paulo","Minas Gerais","Espírito Santo",
"Bahia","Pernambuco","Rio Grande do Sul","Acre"};
JButton exibir;
JLabel rotulo;
public ExemploJList3(){
super("Exemplo de List");
Container tela = getContentPane();
setLayout(null);
exibir = new JButton("Exibir");
rotulo = new JLabel("");
lista = new JList(cidades);
lista.setVisibleRowCount(5);
JScrollPane painelRolagem = new JScrollPane(lista);
lista.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
painelRolagem.setBounds(40,50,150,100);
exibir.setBounds(270,50,100,30);
rotulo.setBounds(50,150,200,30);
lista.setForeground(Color.blue);
lista.setBackground(Color.yellow);
lista.setFont(new Font("Times New Roman",Font.BOLD,16));
exibir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo.setText("o estado é: "+lista.getSelectedValue().toString());
}
}
);
tela.add(painelRolagem);
tela.add(exibir);
tela.add(rotulo);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploJList3 app = new ExemploJList3();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJPasswordField extends JFrame{
JPasswordField caixa;
JLabel rotulo;
public ExemploJPasswordField(){
super("Exemplo com JPasswordField");
Container tela = getContentPane();
setLayout(null);
rotulo = new JLabel("Senha: ");
caixa = new JPasswordField(10);
rotulo.setBounds(50,20,100,20);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 8 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
caixa.setBounds(50,60,200,20);
tela.add(rotulo);
tela.add(caixa);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
ExemploJPasswordField app = new ExemploJPasswordField();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
public class ExemploJTextArea extends JFrame{
JLabel rotulo;
JTextArea texto;
public ExemploJTextArea(){
super("Exemplo com JTextArea");
Container tela = getContentPane();
tela.setLayout(null);
rotulo = new JLabel ("Endereço");
texto = new JTextArea(20,30);
rotulo.setBounds(50,20,100,20);
texto.setBounds(50,50,250,250);
tela.add(rotulo);
tela.add(texto);
setSize(400, 350);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploJTextArea app = new ExemploJTextArea();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
public class ExemploJTextArea2 extends JFrame{
JLabel rotulo;
JTextArea texto;
public ExemploJTextArea2(){
super("Exemplo com JTextField");
Container tela = getContentPane();
setLayout(null);
rotulo = new JLabel ("Endereço");
texto = new JTextArea(20,30);
rotulo.setBounds(50,20,100,20);
texto.setBounds(50,50,300,250);
texto.setLineWrap(true);
texto.setWrapStyleWord(true);
tela.add(rotulo);
tela.add(texto);
setSize(400, 350);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploJTextArea2 app = new ExemploJTextArea2();
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 8 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploJTextArea3 extends JFrame{
JLabel rotulo;
JTextArea texto;
JScrollPane painelrolagem;
JPanel painel;
public ExemploJTextArea3(){
super("Exemplo com JTextField");
Container tela = getContentPane();
tela.setLayout(null);
rotulo = new JLabel ("Endereço");
rotulo.setBounds(50,20,100,20);
texto = new JTextArea(10,20);
painelrolagem = new JScrollPane(texto);
painelrolagem.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
painelrolagem.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAY
S);
painel = new JPanel();
painel.add(painelrolagem);
painel.setBounds(40,40,250,250);
tela.add(rotulo);
tela.add(painel);
setSize(300, 280);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploJTextArea3 app = new ExemploJTextArea3();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
public class ExemploJTextArea4 extends JFrame{
JLabel rotulo;
JTextArea texto;
public ExemploJTextArea4(){
super("Exemplo com JTextArea");
Container tela = getContentPane();
tela.setLayout(null);
rotulo = new JLabel ("Endereço");
texto = new JTextArea(20,30);
rotulo.setBounds(50,20,100,20);
texto.setBounds(50,50,250,250);
texto.setForeground(Color.blue);
texto.setBackground(Color.yellow);
texto.setFont(new Font("Comic Sans MS",Font.BOLD+Font.ITALIC,20));
tela.add(rotulo);
tela.add(texto);
setSize(400, 350);
setVisible(true);
setLocationRelativeTo(null);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 8 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
}
public static void main(String args[]){
ExemploJTextArea4 app = new ExemploJTextArea4();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
public class ExemploJTextField extends JFrame{
JLabel rotulo1,rotulo2,rotulo3,rotulo4;
JTextField texto1,texto2,texto3,texto4;
public ExemploJTextField (){
super("Exemplo com JTextField");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel ("Nome");
rotulo2 = new JLabel ("Idade");
rotulo3 = new JLabel ("Telefone");
rotulo4 = new JLabel ("Celular");
texto1 = new JTextField(50);
texto2 = new JTextField(3);
texto3 = new JTextField(10);
texto4 = new JTextField(10);
rotulo1.setBounds(50,20,80,20);
rotulo2.setBounds(50,60,80,20);
rotulo3.setBounds(50,100,80,20);
rotulo4.setBounds(50,140,80,20);
texto1.setBounds(110,20,200,20);
texto2.setBounds(110,60,20,20);
texto3.setBounds(110,100,80,20);
texto4.setBounds(110,140,80,20);
tela.add(rotulo1);
tela.add(rotulo2);
tela.add(rotulo3);
tela.add(rotulo4);
tela.add(texto1);
tela.add(texto2);
tela.add(texto3);
tela.add(texto4);
setSize(400, 250);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploJTextField app = new ExemploJTextField();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
public class ExemploJTextFieldCorLetra extends JFrame{
JLabel rotulo1,rotulo2,rotulo3,rotulo4;
JTextField texto1,texto2,texto3,texto4;
public ExemploJTextFieldCorLetra (){
super("Exemplo com JTextField");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel ("Nome");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 8 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
public class ExemploJTextFieldFundo extends JFrame{
JLabel rotulo1,rotulo2,rotulo3,rotulo4;
JTextField texto1,texto2,texto3,texto4;
public ExemploJTextFieldFundo (){
super("Exemplo com JTextField");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel ("Nome");
rotulo2 = new JLabel ("Idade");
rotulo3 = new JLabel ("Telefone");
rotulo4 = new JLabel ("Celular");
texto1 = new JTextField(50);
texto2 = new JTextField(3);
texto3 = new JTextField(10);
texto4 = new JTextField(10);
rotulo1.setBounds(50,20,80,20);
rotulo2.setBounds(50,60,80,20);
rotulo3.setBounds(50,100,80,20);
rotulo4.setBounds(50,140,80,20);
texto1.setBounds(110,20,200,20);
texto2.setBounds(110,60,20,20);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 8 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
texto3.setBounds(110,100,80,20);
texto4.setBounds(110,140,80,20);
texto1.setBackground(Color.yellow);
texto2.setBackground(Color.green);
texto3.setBackground(new Color(182,105,126));
texto4.setBackground(new Color(205,255,126));
tela.add(rotulo1);
tela.add(rotulo2);
tela.add(rotulo3);
tela.add(rotulo4);
tela.add(texto1);
tela.add(texto2);
tela.add(texto3);
tela.add(texto4);
setSize(400, 250);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploJTextFieldFundo app = new ExemploJTextFieldFundo();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
public class ExemploLabel extends JFrame{
JLabel rotulo1,rotulo2,rotulo3,rotulo4;
public ExemploLabel(){
super("Exemplo com JTextField");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel ("Nome");
rotulo2 = new JLabel ("Idade");
rotulo3 = new JLabel ("Telefone");
rotulo4 = new JLabel ("Celular");
rotulo1.setBounds(50,20,100,20);
rotulo2.setBounds(50,60,100,20);
rotulo3.setBounds(50,100,100,20);
rotulo4.setBounds(50,140,100,20);
rotulo1.setForeground(Color.red);
rotulo2.setForeground(Color.blue);
rotulo3.setForeground(new Color(190,152,142));
rotulo4.setForeground(new Color(201,200,100));
rotulo1.setFont(new Font("Arial",Font.BOLD,14));
rotulo2.setFont(new Font("Comic Sans MS",Font.BOLD,16));
rotulo3.setFont(new Font("Courier New",Font.BOLD,18));
rotulo4.setFont(new Font("Times New Roman",Font.BOLD,20));
tela.add(rotulo1);
tela.add(rotulo2);
tela.add(rotulo3);
tela.add(rotulo4);
setSize(400, 250);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploLabel app = new ExemploLabel();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 8 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploMinusculas extends JFrame{
JButton copiar,limpar;
JLabel rotulo1,rotulo2;
JTextField texto1,texto2;
public ExemploMinusculas(){
super("Exemplo de saídas minúsculas");
Container tela = getContentPane();
tela.setLayout(null);
rotulo1 = new JLabel("Nome: ");
rotulo2 = new JLabel("Nome: ");
texto1 = new JTextField(20);
texto2 = new JTextField(20);
copiar = new JButton("Copiar");
limpar = new JButton("Limpar");
rotulo1.setBounds(20,30,50,20);
rotulo2.setBounds(20,60,50,20);
texto1.setBounds(60,30,180,20);
texto2.setBounds(60,60,180,20);
copiar.setBounds(20,130,100,20);
limpar.setBounds(180,130,100,20);
copiar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String texto;
texto = texto1.getText().toUpperCase();
texto1.setText(texto);
texto2.setText(texto1.getText().toLowerCase());}});
limpar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto1.setText("");
texto2.setText("");
texto1.requestFocus();}});
tela.add(rotulo1);
tela.add(rotulo2);
tela.add(texto1);
tela.add(texto2);
tela.add(copiar);
tela.add(limpar);
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploMinusculas app = new ExemploMinusculas();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploMaiusculas extends JFrame{
JButton copiar,limpar;
JLabel rotulo1,rotulo2;
JTextField texto1,texto2;
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 8 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
public ExemploMaiusculas(){
super("Exemplo de saídas maiúsculas");
Container tela = getContentPane();
tela.setLayout(null);
rotulo1 = new JLabel("Nome: ");
rotulo2 = new JLabel("Nome: ");
texto1 = new JTextField(20);
texto2 = new JTextField(20);
copiar = new JButton("Copiar");
limpar = new JButton("Limpar");
rotulo1.setBounds(20,30,50,20);
rotulo2.setBounds(20,60,50,20);
texto1.setBounds(60,30,180,20);
texto2.setBounds(60,60,180,20);
copiar.setBounds(20,130,100,20);
limpar.setBounds(180,130,100,20);
copiar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto2.setText(texto1.getText().toUpperCase());}});
limpar.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto1.setText("");
texto2.setText("");
texto1.requestFocus();}});
tela.add(rotulo1);
tela.add(rotulo2);
tela.add(texto1);
tela.add(texto2);
tela.add(copiar);
tela.add(limpar);
setSize(300,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploMaiusculas app = new ExemploMaiusculas();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploRadioButton extends JFrame{
JRadioButton primeira,segunda,terceira,quarta,quinta;
JLabel rotulo,rotulo2;
JButton exibir;
ButtonGroup grupo;
public ExemploRadioButton(){
super("Exemplo de um JRadioButton");
Container tela = getContentPane();
tela.setLayout(null);
rotulo = new JLabel("Escolha uma cidade: ");
rotulo.setBounds(50,20,200,20);
rotulo2 = new JLabel("");
rotulo2.setBounds(150,240,400,20);
exibir = new JButton ("Exibir");
exibir.setBounds(200,200,120,20);
primeira = new JRadioButton("Rio de Janeiro");
segunda = new JRadioButton("São Paulo");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 8 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploSplashScreen extends JFrame{
TelaInicial inicio;
JButton botaosair;
public ExemploSplashScreen(){
super("Exemplo de Splash Screen");
Container tela = getContentPane();
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 9 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
tela.setLayout(null);
inicio = new TelaInicial();
inicio.setVisible(true);
botaosair = new JButton ("Sair");
botaosair.setBounds(100,50,100,20);
botaosair.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
} } );
tela.add(botaosair);
setSize(300, 150);
setLocationRelativeTo(null);
}
public static void main(String args[]){
ExemploSplashScreen app = new ExemploSplashScreen();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void principal(){
setVisible(true);
}
private class TelaInicial extends JWindow{
public TelaInicial(){
Container tela = getContentPane();
tela.setLayout(new FlowLayout(FlowLayout.LEFT,1,1));
ImageIcon imagem = new ImageIcon("imagens/fundo.gif");
JLabel rotulo = new JLabel(imagem);
tela.add(rotulo);
ActionListener fechar = new ActionListener(){
public void actionPerformed(ActionEvent e){
setVisible(false);
dispose();
principal();}};
javax.swing.Timer timer = new javax.swing.Timer(5000,fechar);
timer.start();
pack();
setLocationRelativeTo(null);
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExemploTraduzir extends JFrame{
JButton botao;
public ExemploTraduzir(){
super("Exemplo Traduzir Botões");
Container tela = getContentPane();
tela.setLayout(null);
botao = new JButton("Sair");
botao.setBounds(100,90,100,20);
botao.setToolTipText("Botão que finaliza a janela");
tela.add(botao);
botao.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
int opcao;
Object[] botoes = {"Sim","Não"};
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 9 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.text.DecimalFormat;
import javax.swing.Timer;
public class Hora extends JFrame{
JLabel rotulo;
int hh,mm,ss,h;
Calendar hora;
DecimalFormat formato;
public Hora(){
super("Exemplo de Hora");
Container tela = getContentPane();
tela.setLayout(null);
rotulo = new JLabel("");
rotulo.setBounds(20,30,280,20);
ActionListener tarefa = (new ActionListener(){
public void actionPerformed(ActionEvent e){
HORAS();
}
});
javax.swing.Timer time = new javax.swing.Timer(1000,tarefa);
time.start();
tela.add(rotulo);
setSize(300, 200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
Hora app = new Hora();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void HORAS(){
hora = Calendar.getInstance();
hh = hora.get(Calendar.HOUR_OF_DAY);
mm = hora.get(Calendar.MINUTE);
ss = hora.get(Calendar.SECOND);
formato = new DecimalFormat("00");
rotulo.setText("Hora: "+formatar(hh%12)+":"+formatar(mm)+":"+formatar(ss));
}
private String formatar(int num){
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 9 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Incluir extends JFrame{
JButton botao;
JLabel lnome, ltel1,ltel2,lcel;
JTextField tnome,ttel1,ttel2,tcel;
public Incluir(){
super("Inclusão de Registro");
Container tela = getContentPane();
tela.setLayout(null);
lnome = new JLabel("Nome: ");
ltel1 = new JLabel("Telefone 1: ");
ltel2 = new JLabel("Telefone 2: ");
lcel = new JLabel("Celular: ");
tnome = new JTextField(50);
ttel1 = new JTextField(15);
ttel2 = new JTextField(15);
tcel = new JTextField(15);
botao = new JButton("Incluir Registro");
lnome.setBounds(20,30,80,20);
ltel1.setBounds(20,70,80,20);
ltel2.setBounds(20,110,80,20);
lcel.setBounds(20,150,80,20);
tnome.setBounds(100,30,280,20);
ttel1.setBounds(100,70,100,20);
ttel2.setBounds(100,110,100,20);
tcel.setBounds(100,150,100,20);
botao.setBounds(110,190,150,20);
tela.add(lnome);
tela.add(ltel1);
tela.add(ltel2);
tela.add(lcel);
tela.add(tnome);
tela.add(ttel1);
tela.add(ttel2);
tela.add(tcel);
tela.add(botao);
botao.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO Cadastro (Nome, Telefone_1, Telefone_2,
Celular) VALUES
('"+tnome.getText()+"','"+ttel1.getText()+"','"+ttel2.getText()+"','"+tcel.getText()+"')");
tnome.setText("");
ttel1.setText("");
ttel2.setText("");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 9 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
tcel.setText("");
tnome.requestFocus();
JOptionPane.showMessageDialog(null,"Registro Inserido Com
Sucesso","Mensagem do Programa",JOptionPane.INFORMATION_MESSAGE);
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não
estabelecida","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
}});
setSize(400, 250);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
Incluir app = new Incluir();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Incluir2 extends JFrame{
JButton botao;
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3,t4,t5,t6;
String result;
public Incluir2(){
super("Inclusão de Registro");
Container tela = getContentPane();
tela.setLayout(null);
l1 = new JLabel("Código: "); t1 = new JTextField(5);
l2 = new JLabel("Nome: "); t2 = new JTextField(50);
l3 = new JLabel("Idade: "); t3 = new JTextField(2);
l4 = new JLabel("Data Nasc.: "); t4 = new JTextField(10);
l5 = new JLabel("Salário: "); t5 = new JTextField(15);
l6 = new JLabel("Deficiência: "); t6 = new JTextField(5);
l1.setBounds(20,30,80,20); t1.setBounds(100,30,150,20);
t1.setText("AutoNumeração S/V"); t1.setEnabled(false);
l2.setBounds(20,70,80,20); t2.setBounds(100,70,300,20); t2.requestFocus();
l3.setBounds(20,110,80,20);t3.setBounds(100,110,30,20);
l4.setBounds(20,150,80,20);t4.setBounds(100,150,100,20);
l5.setBounds(20,190,80,20);t5.setBounds(100,190,70,20);
l6.setBounds(20,230,80,20);t6.setBounds(100,230,70,20);
botao = new JButton("Incluir Registro"); botao.setBounds(110,270,150,20);
tela.add(l1);tela.add(t1);
tela.add(l2);tela.add(t2);
tela.add(l3);tela.add(t3);
tela.add(l4);tela.add(t4);
tela.add(l5);tela.add(t5);
tela.add(l6);tela.add(t6);
tela.add(botao);
botao.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 9 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
if ((t6.getText().equals("s")) || (t6.getText().equals("S")))
result = "1";
else if ((t6.getText().equals("n")) || (t6.getText().equals("N")))
result = "0";
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO Tabela1 (Nome, Idade, Dn, Sal, Def)
VALUES ('"+t2.getText()+"',"+t3.getText()+",#"+t4.getText()+"#,"+t5.getText()+","+result+")");
t1.setText(""); t2.setText(""); t3.setText(""); t4.setText(""); t5.setText("");t6.setText("");
t2.requestFocus();
JOptionPane.showMessageDialog(null,"Registro Inserido Com
Sucesso","Mensagem do Programa",JOptionPane.INFORMATION_MESSAGE);
st.close();
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida \n
Comandos Digitados Inválidos","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
}});
setSize(450, 350);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
Incluir2 app = new Incluir2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
public class JanelaCentralizada extends JFrame{
public JanelaCentralizada(){
super("Janela Centralizada");
setSize(300, 150);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
JanelaCentralizada app = new JanelaCentralizada();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
public class JanelaMaximizada extends JFrame{
public JanelaMaximizada(){
super("Como exibir a janela maximizada");
setSize(300, 150);
setVisible(true);
setExtendedState(MAXIMIZED_BOTH);
}
public static void main(String args[]){
JanelaMaximizada app = new JanelaMaximizada();
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 9 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
public class JanelaMinimizada extends JFrame{
public JanelaMinimizada(){
super("Como exibir a janela minimizada");
setSize(300, 150);
setVisible(true);
setExtendedState(ICONIFIED);
}
public static void main(String args[]){
JanelaMinimizada app = new JanelaMinimizada();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Limpar extends JFrame{
JLabel rotulo1, rotulo2;
JTextField texto1,texto2;
JButton limpar;
public Limpar(){
super("Exemplo Limpar");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel("1º Número: "); rotulo2 = new JLabel("2º Número: ");
texto1 = new JTextField(5);texto2 = new JTextField(5);
limpar = new JButton("Limpar");
rotulo1.setBounds(50,20,100,20); rotulo2.setBounds(50,60,100,20);
texto1.setBounds(120,20,200,20); texto2.setBounds(120,60,200,20);
limpar.setBounds(150,100,80,20);
limpar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
texto1.setText(null);
texto2.setText(null);
texto1.requestFocus();
}
}
);
tela.add(rotulo1); tela.add(rotulo2);
tela.add(texto1); tela.add(texto2);
tela.add(limpar);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
Limpar app = new Limpar();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 9 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 9 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import java.awt.*;
import java.awt.event.*;
public class NovaJanela extends JFrame{
JButton abrir;
Inicial segundajanela;
public NovaJanela(){
super("Abrir uma nova janela");
Container tela = getContentPane();
tela.setLayout(null);
abrir = new JButton("Abrir");
abrir.setBounds(100,50,80,20);
abrir.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
segundajanela = new Inicial();
segundajanela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
segundajanela.setVisible(true);
setVisible(false);
dispose();}});
tela.add(abrir);
setSize(300, 150);
setVisible(true);
setLocationRelativeTo(null);}
public static void main(String args[]){
NovaJanela app = new NovaJanela();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}
private class Inicial extends JFrame{
JButton sair;
private Inicial(){
super("Menu Principal...");
Container tela = getContentPane();
tela.setLayout(null);
sair = new JButton("Sair");
sair.setBounds(50,50,100,20);
TBsair tsair = new TBsair();
sair.addActionListener(tsair);
tela.add(sair);
setSize(200,200);
setLocationRelativeTo(null);} }
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NovaJanela2 extends JFrame{
JButton abrir;
Inicial segundajanela;
public NovaJanela2(){
super("Abrir uma nova janela");
Container tela = getContentPane();
tela.setLayout(null);
abrir = new JButton("Abrir");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 9 8
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
abrir.setBounds(100,50,80,20);
abrir.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
segundajanela = new Inicial(null,"Segunda Janela",true);
segundajanela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
segundajanela.setVisible(true);
}});
tela.add(abrir);
setSize(300, 150);
setVisible(true);
setLocationRelativeTo(null);}
public static void main(String args[]){
NovaJanela2 app = new NovaJanela2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}
private class Inicial extends JDialog{
JButton sair;
public Inicial(Frame owner, String title,boolean modal){
super(owner,title,modal);
Container tela1 = getContentPane();
tela1.setLayout(null);
sair = new JButton("Sair");
sair.setBounds(50,50,100,20);
TBsair tsair = new TBsair();
sair.addActionListener(tsair);
tela1.add(sair);
setSize(200,200);
setLocationRelativeTo(null);} }
private class TBsair implements ActionListener{
public void actionPerformed(ActionEvent evento){
int status = JOptionPane.showConfirmDialog(null,"Deseja realmente fechar o
programa?","Mensagem de saída",JOptionPane.YES_NO_OPTION);
if (status == JOptionPane.YES_OPTION)
{segundajanela.setVisible(false);
segundajanela.dispose();}}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NovaJanela4 extends JFrame{
JButton abrir;
Inicial segundajanela;
public NovaJanela4(){
super("Abrir uma nova janela");
Container tela = getContentPane();
tela.setLayout(null);
abrir = new JButton("Abrir");
abrir.setBounds(100,50,80,20);
abrir.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
segundajanela = new Inicial(null,"Segunda Janela",false);
segundajanela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
segundajanela.setVisible(true);
}});
tela.add(abrir);
setSize(300, 150);
setVisible(true);
setLocationRelativeTo(null);}
public static void main(String args[]){
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 1 9 9
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OcultarExibir extends JFrame{
JLabel rotulo1, rotulo2;
JButton ocultar,exbir;
public OcultarExibir(){
super("Exemplo de ocultar e exibir componente");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel("Rótulo 1");
rotulo2 = new JLabel("Rótulo 2");
ocultar = new JButton("Ocultar ");
exbir = new JButton("Exibir ");
rotulo1.setBounds(50,20,100,20);
rotulo2.setBounds(50,60,100,20);
ocultar.setBounds(100,100,80,20);
exbir.setBounds(250,100,80,20);
ocultar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo1.setVisible(false);
rotulo2.setVisible(false);
}
}
);
exbir.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
rotulo1.setVisible(true);
rotulo2.setVisible(true);
}
}
);
tela.add(rotulo1); tela.add(rotulo2);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 0 0
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
tela.add(ocultar); tela.add(exbir);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
OcultarExibir app = new OcultarExibir();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
public class PrimeiraJanela extends JFrame{
public PrimeiraJanela(){
super("Nossa primeira janela");
setSize(300, 150);
setVisible(true);
}
public static void main(String args[]){
PrimeiraJanela app = new PrimeiraJanela();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import java.util.*;
public class Relatorio extends JFrame{
private Connection con;
private JTable tabela;
public Relatorio(){
super("Agenda - Nomes" );
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
try{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
con = DriverManager.getConnection(url, usuario, senha);
}
catch (Exception e){
JOptionPane.showMessageDialog(null,"Conexão não estabelecida","Mensagem do
Programa",JOptionPane.ERROR_MESSAGE);
}
buscaTabela();
setSize(600,200);
setVisible(true);
}
public static void main(String args[]){
Relatorio app = new Relatorio();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void buscaTabela(){
Statement st;
ResultSet res;
try{
Vector cabecalho = new Vector();
Vector linhas = new Vector();
st = con.createStatement();
res = st.executeQuery("SELECT * FROM Cadastro ORDER BY Nome");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 0 1
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
res.next();
ResultSetMetaData rsmd = res.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
cabecalho.addElement(rsmd.getColumnName(i));
do{
linhas.addElement(proximaLinha(res,rsmd));
}
while (res.next());
tabela = new JTable(linhas,cabecalho);
JScrollPane scroller = new JScrollPane( tabela );
getContentPane().add(scroller, BorderLayout.CENTER);
validate();
st.close();
}
catch (SQLException sqlex){
}
}
private Vector proximaLinha(ResultSet rs, ResultSetMetaData rsmd){
Vector LinhaAtual = new Vector();
try{
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
switch(rsmd.getColumnType(i)){
case Types.VARCHAR: LinhaAtual.addElement(rs.getString(i));
break;
case Types.TIMESTAMP: LinhaAtual.addElement(rs.getDate(i));
break;
case Types.NUMERIC: LinhaAtual.addElement(new Long(rs.getLong(i)));
break;
}
}
catch(SQLException e){
}
return LinhaAtual;
}
}
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import java.util.*;
public class Relatorio1 extends JFrame{
JLabel l;
JTextField t;
JButton b;
Inicial janela;
public Relatorio1(){
super("Agenda - Nomes" );
Container tela = getContentPane();
setLayout(null);
l = new JLabel("Nome: "); l.setBounds(20,20,100,20);
t = new JTextField(50); t.setBounds(20,50,250,20);
b = new JButton("Exibir Relatório"); b.setBounds(100,90,150,20);
tela.add(l);tela.add(t);tela.add(b);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
janela = new Inicial();
janela.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
janela.setVisible(true);
}});
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 0 2
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
setSize(400,200);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
Relatorio1 app = new Relatorio1();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class Inicial extends JFrame{
private Connection con;
private JTable tabela;
private Inicial(){
super("Agenda - Nomes" );
setSize(400,300);
setLocationRelativeTo(null);
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
try
{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
con = DriverManager.getConnection(url, usuario, senha);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"Conexão não estabelecida","Mensagem do
Programa",JOptionPane.ERROR_MESSAGE);
}
buscaTabela();
}
private void buscaTabela(){
Statement st;
ResultSet res;
try {
Vector cabecalho = new Vector();
Vector linhas = new Vector();
st = con.createStatement();
res = st.executeQuery("SELECT * FROM Nomes WHERE Nome
LIKE'%"+t.getText()+"%'");
res.next();
ResultSetMetaData rsmd = res.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
cabecalho.addElement(rsmd.getColumnName(i));
do
{
linhas.addElement(proximaLinha(res,rsmd));
}
while (res.next());
tabela = new JTable(linhas,cabecalho);
JScrollPane scroller = new JScrollPane( tabela );
getContentPane().add(scroller, BorderLayout.CENTER);
validate();
st.close();
}
catch (SQLException sqlex) {
}
}
private Vector proximaLinha(ResultSet rs, ResultSetMetaData rsmd )
{
Vector LinhaAtual = new Vector();
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 0 3
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
try
{
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
switch(rsmd.getColumnType(i))
{
case Types.VARCHAR: LinhaAtual.addElement(rs.getString(i));
break;
case Types.TIMESTAMP: LinhaAtual.addElement(rs.getDate(i));
break;
case Types.INTEGER: LinhaAtual.addElement(new Long(rs.getLong(i)));
break;
}
}
catch(SQLException e) {
}
return LinhaAtual;
}
}
}
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import java.util.*;
public class Relatorio2 extends JFrame{
private Connection con;
private JTable tabela;
public Relatorio2(){
super("Agenda - Nomes" );
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
try{
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
con = DriverManager.getConnection(url, usuario, senha);
}
catch (Exception e){
JOptionPane.showMessageDialog(null,"Conexão não estabelecida","Mensagem do
Programa",JOptionPane.ERROR_MESSAGE);
}
buscaTabela();
setSize(600,200);
setVisible(true);
}
public static void main(String args[]){
Relatorio2 app = new Relatorio2();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void buscaTabela(){
Statement st;
ResultSet res;
try{
Vector cabecalho = new Vector();
Vector linhas = new Vector();
st = con.createStatement();
res = st.executeQuery("SELECT
Tabela1.Cod,Tabela1.Nome,Tabela1.Idade,Tabela1.Dn,Tabela1.Sal,Tabela1.Def,Cadastro.Tel
efone_1,Cadastro.Telefone_2,Cadastro.Celular FROM Cadastro, Tabela1 WHERE
Cadastro.Nome=Tabela1.Nome");
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 0 4
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
res.next();
ResultSetMetaData rsmd = res.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
cabecalho.addElement(rsmd.getColumnName(i));
do{
linhas.addElement(proximaLinha(res,rsmd));
}
while (res.next());
tabela = new JTable(linhas,cabecalho);
JScrollPane scroller = new JScrollPane( tabela ) ;
getContentPane().add(scroller, BorderLayout.CENTER);
validate();
st.close();
}
catch (SQLException sqlex){
}
}
private Vector proximaLinha(ResultSet rs, ResultSetMetaData rsmd){
Vector LinhaAtual = new Vector();
try{
for (int i = 1; i <= rsmd.getColumnCount(); ++i)
switch(rsmd.getColumnType(i)){
case Types.VARCHAR: LinhaAtual.addElement(rs.getString(i));
break;
case Types.INTEGER: LinhaAtual.addElement(new Long(rs.getLong(i)));
break;
case Types.TIMESTAMP: LinhaAtual.addElement(rs.getDate(i));
break;
case Types.NUMERIC: LinhaAtual.addElement(rs.getDouble(i));
break;
case Types.BIT: LinhaAtual.addElement(rs.getByte(i));
break;
}
}
catch(SQLException e){
}
return LinhaAtual;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SenhaDigitada extends JFrame{
JPasswordField caixa;
JLabel rotulo, exibir;
JButton mostrar;
public SenhaDigitada(){
super("Exemplo com JPasswordField");
Container tela = getContentPane();
setLayout(null);
rotulo = new JLabel("Senha: ");
caixa = new JPasswordField(10);
exibir = new JLabel("A senha digitada é: ");
mostrar = new JButton("Mostrar");
exibir.setVisible(false);
rotulo.setBounds(50,20,100,20);
caixa.setBounds(50,60,200,20);
exibir.setBounds(50,120,200,20);
mostrar.setBounds(150,100,80,20);
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 0 5
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
mostrar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
String senha = new String(caixa.getPassword());
exibir.setVisible(true);
exibir.setText(senha);
}
}
);
tela.add(rotulo);
tela.add(caixa);
tela.add(exibir);
tela.add(mostrar);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
SenhaDigitada app = new SenhaDigitada();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Soma extends JFrame{
JLabel rotulo1, rotulo2,exibir;
JTextField texto1,texto2;
JButton somar;
public Soma(){
super("Exemplo de soma");
Container tela = getContentPane();
setLayout(null);
rotulo1 = new JLabel("1º Número: "); rotulo2 = new JLabel("2º Número: ");
texto1 = new JTextField(5);texto2 = new JTextField(5);
exibir = new JLabel(""); somar = new JButton("Somar");
rotulo1.setBounds(50,20,100,20); rotulo2.setBounds(50,60,100,20);
texto1.setBounds(120,20,200,20); texto2.setBounds(120,60,200,20);
exibir.setBounds(50,120,200,20); somar.setBounds(150,100,80,20);
somar.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
int numero1,numero2,soma;
soma=0;
numero1 = Integer.parseInt(texto1.getText());
numero2 = Integer.parseInt(texto2.getText());
soma = numero1 + numero2;
exibir.setVisible(true);
exibir.setText("A soma é: "+soma);
}
}
);
exibir.setVisible(false);
tela.add(rotulo1); tela.add(rotulo2);
tela.add(texto1); tela.add(texto2);
tela.add(exibir); tela.add(somar);
setSize(400, 250);
setVisible(true);
}
public static void main(String args[]){
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 0 6
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
import javax.swing.*;
public class TamanhoFixo extends JFrame{
public TamanhoFixo(){
super("Uma janela não dimensionável");
setResizable(false);
setSize(300, 150);
setVisible(true);
}
public static void main(String args[]){
TamanhoFixo app = new TamanhoFixo();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class TestaConexao extends JFrame{
JButton botao;
public TestaConexao(){
super("Testando a Conexão...");
Container tela = getContentPane();
tela.setLayout(null);
botao = new JButton("Verificar Conexão");
botao.setBounds(50,50,150,20);
botao.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
try {
String url = "jdbc:odbc:Agenda";
String usuario = "";
String senha = "";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,usuario,senha);
JOptionPane.showMessageDialog(null,"Conexão estabelecida","Mensagem do
Programa",JOptionPane.INFORMATION_MESSAGE);
con.close();
}
catch(Exception event)
{
JOptionPane.showMessageDialog(null,"Conexão não
estabelecida","Mensagem do Programa",JOptionPane.ERROR_MESSAGE);
}
}});
tela.add(botao);
setSize(300, 150);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]){
TestaConexao app = new TestaConexao();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 0 7
A p o s t i l a d e J a v a 2 C o m B a n c o d e D a d o s
A l e k s a n d r a R . C a r d o z o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . P á g i n a 2 0 8