Input dialog para receber 2 datas

1 resposta
bacoco

Olá estou tentando fazer algo realtivamente simples porém estou me confudindo...
Preciso chamar um metodo que crie 2 formatedtextfield para que o usuario insira 2 datas,inicial e final.

Após isso preciso pegar o valor dessas duas datas para gerar o relatorio,o problema está em criar está tela e em pegar os valores depois, preciso que o valor inserido seja dd/MM/yyyy e entre em um sql.date yyyy-MM-dd

Também quero fazer para que a data maxima seja o dia atual tanto para inicio e fim, também fazendo com que a data de inical não supere a final do contrario enviar mensagem de alerta

Pois bem eis o que tentei:
JFormattedTextField dtInicio = new JFormattedTextField();
      JFormattedTextField dtFim = new JFormattedTextField();
      
      dtInicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));
      dtInicio.setToolTipText("Digite a data no formato DIA/MÊS/ANO exemplo: 01/02/2013 *01 Fevereiro de 2013*.");
      
      dtFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));
      dtFim.setToolTipText("Digite a data no formato DIA/MÊS/ANO exemplo: 01/02/2013 *01 Fevereiro de 2013*.");
      
      MaskFormatter format; 
        try {
            format = new MaskFormatter("##/##/####");
            format.install(dtInicio);
        } catch (ParseException ex) {
            Logger.getLogger(DadosPreventiva.class.getName()).log(Level.SEVERE, null, ex);
        }
        

        try {
            format = new MaskFormatter("##/##/####");
            format.install(dtFim);
        } catch (ParseException ex) {
            Logger.getLogger(DadosPreventiva.class.getName()).log(Level.SEVERE, null, ex);
        }
        
//        Date atual = new Date(System.currentTimeMillis());
//        String dia = Integer.toString(atual.getDay());
//        String mes = Integer.toString(atual.getMonth()+1);
//        String ano = Integer.toString(atual.getYear()+1900);
//        dtFim.setText(dia+mes+ano);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("Insira o periodo que deseja"));
      myPanel.add(Box.createVerticalStrut(20));
      myPanel.add(new JLabel("Inicio:"));
      myPanel.add(dtInicio);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("Fim:"));
      myPanel.add(dtFim);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Periodo", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         dtInicio.getText();
         dtFim.getText();
         
         SimpleDateFormat formato;  
         formato = new SimpleDateFormat("yyyy-MM-dd");
         try {
            java.sql.Date dataInicio = new java.sql.Date(formato.parse(dtInicio.getText()).getTime());
            java.sql.Date dataFim = new java.sql.Date(formato.parse(dtFim.getText()).getTime());
         } catch (ParseException ex) {
            Logger.getLogger(GestorView.class.getName()).log(Level.SEVERE, null, ex);
         }
         
      }

ps: No Delphi eu fazia esse tipo de tarefa com um datetimepicker, no JAVA não teria algo semelhante? Sempre vejo pessoas usando o formatedtextfield para falar manipular datas...

Obrigado

1 Resposta

A

Ola bacoco,

para obter a data você deve realizar o parse com o formato que está no campo que é "dd/MM/yyyy" daí depois na hora que você converter o java.util.Date para o java.sql.Date ele reconhecerá corretamente. Exemplo:
SimpleDateFormat formato;  
            formato = new SimpleDateFormat("dd/MM/yyyy");
            try {
                java.sql.Date dataInicio = new java.sql.Date(formato.parse(dtInicio.getText()).getTime());
                java.sql.Date dataFim = new java.sql.Date(formato.parse(dtFim.getText()).getTime());

realizei a validação do alerta com o evento focusLost do FocusListener,

Exemplo:
dtInicio.addFocusListener(new FocusListener() {
			
			public void focusLost(FocusEvent e) {
				JFormattedTextField dataInicio = (JFormattedTextField)e.getComponent();
				JFormattedTextField dataFim = null;
				SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
				try {
					dataFim = buscaOutroFormatter(dataInicio);
					if(!dataFim.getText().isEmpty() && !dataFim.getText().split("/")[0].equalsIgnoreCase("  ")){
						Date dateFim = formato.parse(dataFim.getText());
						Date dateInicio = formato.parse(dataInicio.getText());
						try {
							validacaoData(dateInicio, dateFim);
						} catch (Exception e1) {
							JOptionPane.showMessageDialog(null, e1.getMessage());
						}
					}
				} catch (ParseException e1) {
					JOptionPane.showMessageDialog(null, "Informe uma data correta, " +
							"\nDigite a data no formato DIA/MÊS/ANO exemplo: 01/02/2013 *01 Fevereiro de 2013*.");
					e1.printStackTrace();
					dataInicio.setText("");
				}
			}
			
			public void focusGained(FocusEvent e) {
			}
		});

segue abaixo uma classe "Teste" com a implementação desejada por você:

import java.awt.Component;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.Box;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;
/**
 * Write a description of class Teste here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Teste
{
    public static void main(String args[]){
        metodo();
    }

    private static void validacaoData(Date dataInicial, Date dataFinal) throws Exception{
        if(dataInicial.after(dataFinal) || 
        dataInicial.after(new Date()) || 
        dataFinal.after(new Date())) {
            throw new Exception ("Informe um periodo com intervalo real, " +
                "\ninferior a data de hoje e data final maior que data inicial !");
        }
    }

    private static JFormattedTextField buscaOutroFormatter(Component componenteFilho){
        for(Component c : componenteFilho.getParent().getComponents()){
            if(c instanceof JFormattedTextField && 
            (JFormattedTextField)c != componenteFilho){
                return (JFormattedTextField)c;
            }
        }
        return null;
    }

    public static void metodo(){
        JFormattedTextField dtInicio = new JFormattedTextField();
        JFormattedTextField dtFim = new JFormattedTextField();

        dtInicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));
        dtInicio.setToolTipText("Digite a data no formato DIA/MÊS/ANO exemplo: 01/02/2013 *01 Fevereiro de 2013*.");

        dtFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));
        dtFim.setToolTipText("Digite a data no formato DIA/MÊS/ANO exemplo: 01/02/2013 *01 Fevereiro de 2013*.");

        MaskFormatter format; 
        try {
            format = new MaskFormatter("##/##/####");
            format.install(dtInicio);
        } catch (ParseException ex) {
            Logger.getLogger("CLASSE").log(Level.SEVERE, null, ex);
        }

        try {
            format = new MaskFormatter("##/##/####");
            format.install(dtFim);
        } catch (ParseException ex) {
            Logger.getLogger("CLASSE").log(Level.SEVERE, null, ex);
        }

        dtInicio.addFocusListener(new FocusListener() {

                public void focusLost(FocusEvent e) {
                    JFormattedTextField dataInicio = (JFormattedTextField)e.getComponent();
                    JFormattedTextField dataFim = null;
                    SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
                    try {
                        dataFim = buscaOutroFormatter(dataInicio);
                        if(!dataFim.getText().isEmpty() && !dataFim.getText().split("/")[0].equalsIgnoreCase("  ")){
                            Date dateFim = formato.parse(dataFim.getText());
                            Date dateInicio = formato.parse(dataInicio.getText());
                            try {
                                validacaoData(dateInicio, dateFim);
                            } catch (Exception e1) {
                                JOptionPane.showMessageDialog(null, e1.getMessage());
                            }
                        }
                    } catch (ParseException e1) {
                        JOptionPane.showMessageDialog(null, "Informe uma data correta, " +
                            "\nDigite a data no formato DIA/MÊS/ANO exemplo: 01/02/2013 *01 Fevereiro de 2013*.");
                        e1.printStackTrace();
                        dataInicio.setText("");
                    }
                }

                public void focusGained(FocusEvent e) {
                }
            });

        dtFim.addFocusListener(new FocusListener() {

                public void focusLost(FocusEvent e) {
                    JFormattedTextField dataFim = (JFormattedTextField)e.getComponent();
                    JFormattedTextField dataInicio = null;
                    SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
                    try {
                        dataInicio = buscaOutroFormatter(dataFim);
                        if(!dataInicio.getText().isEmpty() && !dataInicio.getText().split("/")[0].equalsIgnoreCase("  ")){
                            Date dateInicio = formato.parse(dataInicio.getText());
                            Date dateFim = formato.parse(dataFim.getText());
                            try {
                                validacaoData(dateInicio, dateFim);
                            } catch (Exception e1) {
                                JOptionPane.showMessageDialog(null, e1.getMessage());
                            }
                        }
                    } catch (ParseException e1) {
                        JOptionPane.showMessageDialog(null, "Informe uma data correta, " +
                            "\nDigite a data no formato DIA/MÊS/ANO exemplo: 01/02/2013 *01 Fevereiro de 2013*.");
                        e1.printStackTrace();
                        dataFim.setText("");
                    }
                }

                public void focusGained(FocusEvent e) {
                }
            });

        JPanel myPanel = new JPanel();
        myPanel.add(new JLabel("Insira o periodo que deseja"));
        myPanel.add(Box.createVerticalStrut(20));
        myPanel.add(new JLabel("Inicio:"));
        myPanel.add(dtInicio);
        myPanel.add(Box.createHorizontalStrut(15)); // a spacer
        myPanel.add(new JLabel("Fim:"));
        myPanel.add(dtFim);

        int result = JOptionPane.showConfirmDialog(null, myPanel, 
                "Periodo", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            dtInicio.getText();
            dtFim.getText();

            SimpleDateFormat formato;  
            formato = new SimpleDateFormat("dd/MM/yyyy");
            try {
                java.sql.Date dataInicio = new java.sql.Date(formato.parse(dtInicio.getText()).getTime());
                java.sql.Date dataFim = new java.sql.Date(formato.parse(dtFim.getText()).getTime());

                System.out.println("DT INICIO : "+dataInicio.getTime());
                System.out.println("DT FIM : "+dataFim.getTime());

                System.out.println("DT INICIO : "+dataInicio);
                System.out.println("DT FIM : "+dataFim);
            } catch (ParseException ex) {
                Logger.getLogger("CLASSE").log(Level.SEVERE, null, ex);
            }

        }
    }
}

Espero que isso ajude.
Abs!

Criado 30 de janeiro de 2013
Ultima resposta 30 de jan. de 2013
Respostas 1
Participantes 2