quinta-feira, 24 de novembro de 2011

Calendario JAVA

Galera.. fiz uma biblioteca legal

que exibe em um JTextFiel um botão, ao Selecionar nele.. exibe um calendário aonde pode escolher a data

para chamar o campo é como qualquer outro campo

TextDataChooser = new TextDataChooser();

e adicionar no painel!!


Claro que não fiz tudo sozinho.. utilizei algumas classes do Marky.Vasconcelos


download ta aqui!!


http://guj.com.br/java/259131-textdatachooser-calendario-swing#1351520

terça-feira, 22 de novembro de 2011

Conversor de Data JAVA

segue dois métodos que fazem conversão de datas


public Date convertStringToDate(String data){
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = null;
try {
date = (Date)formatter.parse(data);
} catch (ParseException e) {
}
return date;
}


public String convertDatatoString(Date data) {
String strdata;
java.text.SimpleDateFormat formata = new java.text.SimpleDateFormat("dd/MM/yyyy");
strdata = formata.format(data);

return strdata;
}

Conversores de Valor JAVA

Segue dois métodos simples que fazem a conversão de String para Double e de Double para String


public String formataValortoString(double valor) {
DecimalFormat deci = new DecimalFormat("0.00");
String num = String.valueOf(deci.format(valor));
num = num.replace(".", ",");
return num;
}


public double formataValorduasCasas(String valor) {
double num = 0;
valor = valor.replaceAll(",", ".");
DecimalFormat deci = new DecimalFormat("0.00");

num = Double.parseDouble(valor);
valor = deci.format(num);

valor = valor.replaceAll(",", ".");
num = Double.parseDouble(valor);

return num;
}

Classe que Exibe o Relatorio java .jasper

Segue uma classe utilitária para exibir seu relatórios
Ao invés de ter que mexer com sql no relatório, você faz ele de tal forma que apenas passando um List
ele ja exibe os dados

segue a classe


package gerenciador;

import java.util.List;

import javax.swing.JDialog;

import objetos.Empresa;

import relatorios.VerificaOrdem;

import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;

public class Relatorio {

@SuppressWarnings("unchecked")
public static void gerarRelatorio(List lista, String caminho){
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
JDialog viewer = new JDialog(new javax.swing.JFrame(),"Visualização do Relatório", true);
viewer.setSize(screenSize.width, screenSize.height-80);
viewer.setLocationRelativeTo(null);
try {
JRBeanCollectionDataSource jrb = new JRBeanCollectionDataSource(lista);
JasperPrint meuRelatorio = JasperFillManager.fillReport(caminho, null, jrb);
//JOptionPane.showMessageDialog(null, "chegou");
JasperViewer visualizador = new JasperViewer(meuRelatorio, false);
visualizador.setSize(screenSize.width, screenSize.height-80);
viewer.getContentPane().add(visualizador.getContentPane());    
viewer.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}


o metodo gerarRelatorio espera uma lista, e uma string com o caminho

ele cria uma JDialog para visualizar o relatorio, pega o tamanho da tela e diminui 80 pixels da altura
e o JRBeanCollectionDataSource nada mais é do que a lista que exibira os relatorios
é exibido o relatorio

obs* lembrando que se for passar caminho para o relatorio em um diretorio do computador se usa 2 barras invertidas

ex: C:\\sistema\\relatorio\\relatorio.jasper

agora se for utilizar a partir da raiz do programa pode ser

/relatorio/relatorio.jasper

abraço

Login Hibernate JAVA DAO

Vou postar uma Classe que Serve como base para muitos aprenderem a fazer consulta no banco de dados
usando Hibernate

tudo comentado

Usuario


package objetos;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.GeneratedValue;
import javax.persistence.SequenceGenerator;
import javax.persistence.GenerationType;
import java.util.Date;

@Entity
@SequenceGenerator(name = "Usuario_SEQ", sequenceName = "Usuario_SEQ")
@Table(name = "Usuario")
public class Usuario {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "Usuario_SEQ")
@Column(name = "CODIGO")
private Integer codigo;
@Column(name = "login")
private String login;
@Column(name = "senha")
private String senha;
@Column(name = "bloqueado")
private Boolean bloqueado;
@Column(name = "CANCELADO")
private String cancelado;
@Column(name = "CAUSA_CANCEL")
private String causaCancel;
@Column(name = "DATA_ATUALIZACAO")
private Date dataAtualizacao;
@Column(name = "DATA_EXCLUSAO")
private Date dataExcluir;
@Column(name = "DATA_CADASTRO")
private Date dataCadastro;

//getters and setters
}


UsuarioDAO


package dao;

import objetos.Usuario;
import gerador.dao.Dao;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import gerador.util.HibernateUtil;
import java.util.List;

//Classe extende do dao generico
//sendo assim, obtem todos os atributos e metodos da classe pai
//que no caso é o dao
public class UsuarioDAO extends Dao<Usuario> {
// abaixo é o construtor do Usuariodao
public UsuarioDAO() {
// o super funciona como construtor da classe pai
// se observar no Dao.java existe um construtor que espera um .class
// então passamos a classe que queremos manipular
//
super(Usuario.class);
}

// metodo que é chamado nas telas
// retorna uma lista, e esse metodo recebe uma string para fazer uma
// consulta melhor
@SuppressWarnings("unchecked")
public List<Usuario> selecionaUsuario(String texto) throws Exception {
// abaixo ele abre uma sessão com o banco de dados
Session session = null;
try {
// abaixo ele pega a sessão na classe HibernateUtil
session = HibernateUtil.getSession();
// a classe criteria é para refinar as consultar
// fazer um filtro melhor
Criteria criteria = session.createCriteria(Usuario.class);
// pega o texto e separa por espaço
String te[] = texto.split(" ");
// faz um for do tanto de palavras que existem separas por espaço
// exemplo (faculdade fema) existes duas palavras separas por espaço
for (int i = 0; i < te.length; i++) {
// em baixo o filtro sql é realizado
criteria
.add(org.hibernate.criterion.Restrictions
.sqlRestriction("this_.CANCELADO = 'N' and (this_.CODIGO like '%"
+ te[i]
+ "%' or this_.login like '%"
+ te[i]
+ "%' or this_.senha like '%"
+ te[i] + "%') "));
}
// a ordem em que será ordenado
criteria.addOrder(Order.desc("codigo"));
// retorna a lista
return criteria.list();
} catch (Exception e) {
System.out.println(e);
throw e;
} finally {
// fecha a sessão
if (session != null && session.isOpen()) {
session.close();
}
}
}

@SuppressWarnings("unchecked")
// mesmo padrão do metodo acima
public List<Usuario> buscaSimples(String texto) throws Exception {
Session session = null;
try {
session = HibernateUtil.getSession();
Criteria criteria = session.createCriteria(Usuario.class);
String te[] = texto.split(" ");
for (int i = 0; i < te.length; i++) {
criteria
.add(org.hibernate.criterion.Restrictions
.sqlRestriction("this_.CANCELADO = 'N' and (this_.login like '%"
+ te[i] + "%') "));
}
criteria.addOrder(Order.desc("codigo"));
return criteria.list();
} catch (Exception e) {
System.out.println(e);
throw e;
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}

public Usuario buscaLogin(String usuario, String senha) throws Exception {
Session session = null;
try {
session = HibernateUtil.getSession();
Criteria criteria = session.createCriteria(Usuario.class);
criteria.add(org.hibernate.criterion.Restrictions.eq("login",
usuario));
criteria.add(org.hibernate.criterion.Restrictions
.eq("senha", senha));
return (Usuario) criteria.list().get(0);
} catch (Exception e) {
System.out.println(e);
throw e;
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}
}

Imprimir em impressora Matricial JAVA

pessoal.. segue uma classe legal para imprimir em uma impressora Matricial


package gerenciador;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Properties;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class PrinterMatrix {

public String impressora;

    public PrinterMatrix(){    
    try{
    File f = new File("conf.ini");
    if (f.exists()){
    Properties confBanco = new Properties();
    confBanco.load(new FileInputStream("conf.ini"));
    impressora = confBanco.getProperty("impressora");
   
    System.out.print("IMP --->"+impressora);
    }
    } catch (Exception e){
    System.out.println("ERRO DE IMPRESSORA ------> "+e);
    }      
    }

    public void setOutSize(int lin, int col)
    {
        page = new String[lin][col];
    }

    public void printCharAtCol(int lin, int colunaIn, int colunaEnd, String text)
    {
        for(int i = 0; i < colunaEnd; i++)
            if(i >= colunaIn - 1 && i <= colunaEnd - 1)
                page[lin - 1][i] = text;

    }

    public void printCharAtLin(int linhaIn, int linhaEnd, int coluna, String text)
    {
        for(int i = 0; i < linhaEnd; i++)
            if(i >= linhaIn - 1 && i <= linhaEnd - 1)
                page[i][coluna - 1] = text;

    }

    public void printTextLinCol(int lin, int coluna, String text)
    {
    text = RemoveAcentos(text);
        for(int i = 0; i < coluna; i++)
            if(i == coluna - 1)
                page[lin - 1][i] = text;

    }
   
    public String printTextLin(int coluna, String text)
    {
    text = RemoveAcentos(text);
        String newText = "";
        for(int i = 0; i < coluna; i++)
            newText = newText + " ";
        return newText+text;
    }

    public void printCharAtLinCol(int linIn, int linEnd, int colunaIn, int colunaEnd, String text)
    {
        for(int i = 0; i < linEnd; i++)
        {
            if(i < linIn - 1 || i > linEnd - 1)
                continue;
            for(int c = 0; c < colunaEnd; c++)
                if(c >= colunaIn - 1 && c <= colunaEnd - 1)
                    page[i][c] = text;

        }

    }

    public void printTextWrap(int linI, int linE, int colI, int colE, String text)
    {
        int textSize = text.length();
        int limitH = linE - linI;
        int limitV = colE - colI;
        int wrap = 0;
        if(textSize > limitV)
        {
            wrap = textSize / limitV;
            if(textSize % limitV > 0)
                wrap++;
        } else
        {
            wrap = 1;
        }
        System.out.println("textSize:" + textSize);
        System.out.println("limitH:" + limitH);
        System.out.println("limitV:" + limitV);
        System.out.println("wrap:" + wrap);
        String wraped[] = new String[wrap];
        int end = 0;
        int init = 0;
        for(int i = 1; i <= wrap; i++)
        {
            end = i * limitV;
            if(end > text.length())
                end = text.length();
            wraped[i - 1] = text.substring(init, end);
            System.out.println("wraped[" + (i - 1) + "]:" + wraped[i - 1]);
            init = end;
        }

        for(int b = 0; b < wraped.length; b++)
            if(b <= linE)
            {
                page[linI][colI] = wraped[b];
                System.out.println("page[" + linI + "][" + colI + "]:" + page[linI][colI]);
                linI++;
            }

    }

    public void show()
    {
        for(int i = 0; i < page.length; i++)
        {
            for(int b = 0; b < page[i].length;)
            {
                String tmp = page[i][b];
                if(tmp != null && !tmp.equals(""))
                {
                    int size = tmp.length();
                    b += size;
                    System.out.print(tmp);
                } else
                {
                    System.out.print(" ");
                    b++;
                }
            }

            System.out.println();
        }

    }

    public void toFile(String fileName)
    {
        try
        {
            FileOutputStream fo = new FileOutputStream(fileName);
            for(int i = 0; i < page.length; i++)
            {
                for(int b = 0; b < page[i].length;)
                {
                    String tmp = page[i][b];
                    if(tmp != null && !tmp.equals(""))
                    {
                        int size = tmp.length();
                        b += size;
                        fo.write(tmp.getBytes());
                    } else
                    {
                        fo.write(" ".getBytes());
                        b++;
                    }
                }

                fo.write("\n".getBytes());
            }

            fo.flush();
            fo.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void toPrinter(String printerName)
    {
        try
        {
            FileOutputStream fo = new FileOutputStream(printerName);
            for(int i = 0; i < page.length; i++)
            {
                for(int b = 0; b < page[i].length;)
                {
                    String tmp = page[i][b];
                    if(tmp != null && !tmp.equals(""))
                    {
                        int size = tmp.length();
                        b += size;
                        fo.write(tmp.getBytes());
                    } else
                    {
                        fo.write(" ".getBytes());
                        b++;
                    }
                }

                fo.write("\n".getBytes());
            }

            fo.flush();
            fo.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void toPrinter(String printerName, byte escCommands[])
    {
        try
        {
            FileOutputStream fo = new FileOutputStream(printerName);
            fo.write(escCommands);
            for(int i = 0; i < page.length; i++)
            {
                for(int b = 0; b < page[i].length;)
                {
                    String tmp = page[i][b];
                    if(tmp != null && !tmp.equals(""))
                    {
                        int size = tmp.length();
                        b += size;
                        fo.write(tmp.getBytes());
                    } else
                    {
                        fo.write(" ".getBytes());
                        b++;
                    }
                }

                fo.write("\n".getBytes());
            }

            fo.flush();
            fo.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void toPrintStream(PrintStream out)
    {
        try
        {
            for(int i = 0; i < page.length; i++)
            {
                for(int b = 0; b < page[i].length;)
                {
                    String tmp = page[i][b];
                    if(tmp != null && !tmp.equals(""))
                    {
                        int size = tmp.length();
                        b += size;
                        out.print(tmp);
                    } else
                    {
                        out.print(" ");
                        b++;
                    }
                }

                out.println("");
            }

            out.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void toPrinterServer(String ipServer, int port)
    {
        try
        {
            Socket socket = new Socket(ipServer, port);
            System.out.println("Porta:" + socket.getPort());
            System.out.println("Host IP......:" + socket.getInetAddress().getHostAddress());
            System.out.println("Host Name......:" + socket.getInetAddress().getHostName());
            OutputStream fo = socket.getOutputStream();
            StringBuffer saida = new StringBuffer();
            for(int i = 0; i < page.length; i++)
            {
                for(int b = 0; b < page[i].length;)
                {
                    String tmp = page[i][b];
                    if(tmp != null && !tmp.equals(""))
                    {
                        int size = tmp.length();
                        b += size;
                        saida.append(tmp);
                    } else
                    {
                        saida.append(" ");
                        b++;
                    }
                }

                saida.append("\n");
            }

            fo.write(saida.toString().getBytes());
            fo.flush();
            fo.close();
            socket.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public String alinharADireita(int tamCampo, String text)
    {
        int spaces = tamCampo - text.length();
        String newText = "";
        for(int i = 0; i < spaces; i++)
            newText = newText + " ";

        return newText + text;
    }

    public String alinharAEsquerda(int tamCampo, String text)
    {
        int spaces = tamCampo - text.length();
        String newText = "";
        for(int i = 0; i < spaces; i++)
            newText = newText + " ";

        return text + newText;
    }

    public String centralizar(int tamCampo, String text)
    {
        int spaces = (tamCampo - text.length()) / 2;
        String newText = "";
        for(int i = 0; i < spaces; i++)
            newText = newText + " ";
        return newText + text + newText;
    }
   
    public String centralizarcomcaractere(int tamCampo, String text, String caractere)
    {
        int spaces = (tamCampo - text.length()) / 2;
        String newText = "";
        for(int i = 0; i < spaces; i++)
            newText = newText + caractere;
        return newText + text + newText;
    }

    public void mapearDocumento(int linha, int coluna, String printer)
    {
        setOutSize(linha, coluna);
        for(int i = 1; i <= coluna; i++)
        {
            String print = i + "";
            if(i >= 10 && i <= 99)
                print = print.substring(1, 2);
            if(i >= 100 && i <= coluna)
                print = print.substring(2, 3);
            printTextLinCol(1, i, print);
        }

        for(int i = 1; i <= linha; i++)
        {
            String print = "" + i;
            printTextLinCol(i, 1, print);
        }

        toPrinter(printer);
    }

    public void mapearDocumento(int linha, int coluna, String printer, byte escCommands[])
    {
        setOutSize(linha, coluna);
        for(int i = 1; i <= coluna; i++)
        {
            String print = i + "";
            if(i >= 10 && i <= 99)
                print = print.substring(1, 2);
            if(i >= 100 && i <= coluna)
                print = print.substring(2, 3);
            printTextLinCol(1, i, print);
        }

        for(int i = 1; i <= linha; i++)
        {
            String print = "" + i;
            printTextLinCol(i, 1, print);
        }

        toPrinter(printer, escCommands);
    }

    public void mapearDocumentoImageFile(int linha, int coluna, String fileName)
    {
        setOutSize(linha, coluna);
        for(int i = 1; i <= coluna; i++)
        {
            String print = i + "";
            if(i >= 10 && i <= 99)
                print = print.substring(1, 2);
            if(i >= 100 && i <= coluna)
                print = print.substring(2, 3);
            printTextLinCol(1, i, print);
        }

        for(int i = 1; i <= linha; i++)
        {
            String print = "" + i;
            printTextLinCol(i, 1, print);
        }

        toImageFile(fileName);
    }

    public void toImageFile(String fileName)
    {
        int width = page[0].length * 10;
        int height = page.length * 10;
        BufferedImage image = new BufferedImage(width, height, 1);
        Graphics2D g = image.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setPaint(Color.white);
        Rectangle2D rectangle = new java.awt.geom.Rectangle2D.Double(0.0D, 0.0D, width, height);
        g.fill(rectangle);
        GradientPaint gp = new GradientPaint(0.0F, 0.0F, Color.black, 400F, 100F, Color.black);
        g.setPaint(gp);
        try
        {
            for(int i = 0; i < page.length; i++)
            {
                for(int b = 0; b < page[i].length;)
                {
                    String tmp = page[i][b];
                    if(tmp != null && !tmp.equals(""))
                    {
                        int size = tmp.length();
                        g.drawString(tmp, b * 10, (i + 1) * 10);
                        b += size;
                    } else
                    {
                        g.drawString(" ", b * 10, (i + 1) * 10);
                        b++;
                    }
                }

            }

            FileOutputStream file = new FileOutputStream(fileName);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(file);
            JPEGEncodeParam jpegParams = encoder.getDefaultJPEGEncodeParam(image);
            jpegParams.setQuality(1.0F, false);
            encoder.setJPEGEncodeParam(jpegParams);
            encoder.encode(image);
            file.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public String RemoveAcentos(String str){
    char[] acentuados = new char[] { 'ç', 'á', 'à', 'ã', 'â', 'ä', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ó', 'ò', 'õ', 'ô', 'ö', 'ú', 'ù', 'û', 'ü' };
 
    char[] naoAcentuados = new char[] { 'c', 'a', 'a', 'a', 'a', 'a', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u' };
 
    for (int i = 0; i < acentuados.length; i++) {
        str = str.replace(acentuados[i], naoAcentuados[i] );
        str = str.replace(Character.toUpperCase(acentuados[i] ), Character.toUpperCase(naoAcentuados[i] ) );
    }
    return str;
    }
   
    public static void main(String args[])
    {
    System.out.print("");
        PrinterMatrix t = new PrinterMatrix();
        t.setOutSize(15, 70);
        t.printCharAtCol(1, 1, 70, "-");
        t.printTextLinCol(2, 1, "NOME.....:");
        t.printTextLinCol(3, 1, "ENDEREÇO.:");
        t.printTextLinCol(4, 1, "CIDADE...:");
        t.printTextLinCol(5, 1, "ATIVIDADE:");
        t.printTextLinCol(2, 11, "Nome TEste");
        t.printTextLinCol(3, 11, "TESTE PAH");
        t.printTextLinCol(4, 11, "ASSIS SÃO PAULO");
        t.printTextLinCol(5, 11, "ATIVIDADE ATESTEAKLJ ÇLSAKJFAÇSLKDJFASLFJKASDF");
        t.printTextLinCol(6, 1, t.centralizar(70, "CENTRALIZAR"));
        t.toFile("impresso.txt");
        t.show();
       
        t.toImageFile("printermatrix.jpg");
    }

    private String page[][];
}