quinta-feira, 18 de dezembro de 2008

Imagens - 18

Horse

Abrir diretório do Sistema Operacional com Swing

//Este exemplo mostra como selecionar diretório usando
//JFileChooser a partir de uma JFrame

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class ExemploJFileChooser extends JFrame {
public ExemploJFileChooser() {
super("Escolher um diretório usando JFileChooser");

Container c = getContentPane();
FlowLayout layout = new FlowLayout(FlowLayout.CENTER);
c.setLayout(layout);

JButton btn = new JButton("Escolher Arquivo");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();

// restringe a amostra a diretorios apenas
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

int res = fc.showOpenDialog(null);

if (res == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
JOptionPane.showMessageDialog(null,
"Voce escolheu o arquivo: " + file.getName());
} else
JOptionPane.showMessageDialog(null,
"Voce nao selecionou nenhum arquivo.");
}
});

c.add(btn);

setSize(400, 200);
setVisible(true);
}

public static void main(String[] args) {
ExemploJFileChooser app = new ExemploJFileChooser();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

quarta-feira, 17 de dezembro de 2008

Teste de Conexão com Banco de Dados MySQL com JFrame

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();
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:mysql://localhost:3306/agenda";
String usuario = "root";
String senha = "vertrigo";
Class.forName("com.mysql.jdbc.Driver");
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);
}
}

Conexão com banco de dados MySQL - JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCExemplo {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "vertrigo");
System.out.println("Conectado!!!");
con.close();

}catch (SQLException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
System.out.println("Nada");
}
}
}

Adicionando componentes JPasswordField

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);
caixa.setBounds(50, 60, 100, 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);
}
}

Vários botões na janela

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);
}

public static void main(String args[]) {
ExemploBotao app = new ExemploBotao();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Adicionando componentes JButton

import javax.swing.*;
import java.awt.*;

public class ExemploBotao extends JFrame {
JButton botao;

public ExemploBotao() {
super("Exemplo com JButton");
Container tela = getContentPane();
setLayout(null);
botao = new JButton("Procurar");
botao.setBounds(50, 20, 100, 20);
tela.add(botao);
setSize(400, 250);
setVisible(true);
}

public static void main(String args[]) {
ExemploBotao app = new ExemploBotao();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Adicionando elementos JTextField

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);
}
}

Adicionando imagem ao JLabel

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);
}
}

Adicionando componentes JLabel

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);
}
}

Definir um ícone para a janela

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[]) {
DefinirIcone app = new DefinirIcone();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Cor de Fundo de Janelas

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(new Color(255, 128, 128));
setSize(500, 300);
setVisible(true);
}

public static void main(String args[]) {
CorDeFundo app = new CorDeFundo();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Estilos Janelas

import javax.swing.*;

public class Janelas extends JFrame {
public Janelas() {
super("Como exibir a janela maximizada");
setSize(300, 150);
setVisible(true);
//setExtendedState(MAXIMIZED_BOTH); // janela maximizada
//setExtendedState(ICONIFIED); // janela minimizada
//setResizable(false); // não pode ser redimensionada
//setLocationRelativeTo(null); // janela centralizada
}

public static void main(String args[]) {
Janelas app = new Janelas();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Funções Matemáticas

terça-feira, 2 de dezembro de 2008

Implementação de Árvore usando C++

A seguir, postarei os fontes necessários para a implementação de uma árvore. O código não propicia nenhuma interface gráfica para o programa, mas o torna capaz de inserir elementos na árvore e imprimí-los em ordem crescente e decrescente.

Obs.: O método para exclusão de elementos não foi implementado.


#include

using namespace std;

struct noh {
int num;
noh *esq;
noh *dir;
};

//estrutura arvore
struct ArvoreBinaria {
noh *raiz;
int profundidade;
int quantidade;
};

//inicializar arvore
void Inicializa(ArvoreBinaria *arvore){
arvore->raiz = NULL;
arvore->profundidade = -1;
arvore->quantidade = 0;
};

noh *criarnoh(int n) {
noh *novo;
novo = new noh;
if ( novo != NULL ){
novo -> num = n;
novo -> esq = NULL;
novo -> dir = NULL;
};
return (novo);
};

noh *Procurar(noh *elem, int elemproc, int *prof, bool *achou) {
*achou = false;
if (elem == NULL)
return NULL;
*prof = *prof + 1;
if (elemproc > elem -> num){
if (elem -> dir != NULL){
return Procurar(elem -> dir, elemproc,prof,achou);
}else{
return (elem);
}
}else{
if (elemproc <> num){
if (elem -> esq != NULL){
return Procurar(elem -> esq, elemproc,prof,achou);
}else{
return (elem);
}
}else{
//Encontrou o elemento
*achou = true;
return (elem);
}
};
};

int Insere(ArvoreBinaria *arvore, int valor) {
//Verificar se eh o primeiro elemento
if ( arvore->raiz == NULL ) {
arvore->raiz = criarnoh(valor);
if ( arvore->raiz == NULL ){
return -1; //Erro
}else{
arvore->profundidade = 0;
arvore->quantidade = 1;
return 1; //Inserido com sucesso
};
};

//Nao eh o primeiro elemento, procurar se existe
noh *NoElementoOuPai;
int prof = -1;
bool achou = false;
NoElementoOuPai = Procurar(arvore->raiz,valor,&prof,&achou);
if (achou == false){
//Inserir elemento na arvore
noh *novo;
novo = criarnoh(valor);
if ( novo == NULL ){
return -1;
}else{
if ( valor <>num )
NoElementoOuPai -> esq = novo;
else
NoElementoOuPai -> dir = novo;
prof++;
if ( prof > arvore->profundidade )
arvore->profundidade = prof;
arvore->quantidade++;
return 1;
}
}else{
//Encontrou o elemento
return 0;
};
};

void MostraCrescente (noh *elem){
if (elem != NULL){
MostraCrescente(elem -> esq);
cout<<> num << " "; MostraCrescente(elem -> dir);
};
};
void MostraDecrescente (noh *elem){
if (elem != NULL){
MostraCrescente(elem -> dir);
cout<<> num << " "; MostraCrescente(elem -> esq);
};
};

int main(){
ArvoreBinaria *arvore;
arvore = new ArvoreBinaria;
Inicializa (arvore);
int aux = 0;
//int count = 1;
while (aux != -1){
cout<< " Informe o valor: "; cin>> aux;
if (aux != -1)
Insere(arvore, aux);
//count++;
};
int opcao;
cout<< "Deseja ver os elementos em ordem crescente ou decrescente?"; cout<< "\n\n\t crescente: 1\n"; cout<< "\n\t decrescente: 2\n"; cin>>opcao;

switch(opcao){
case 1:
MostraCrescente(arvore->raiz);
break;
case 2:
MostraCrescente(arvore->raiz);
}

system("pause>>null");
return 1;
}

Bom proveito

Imagens - 13

Floco de neve