Home| New Wiki | | Login | User registry | Home Tree PDF
PaperDateField
Owner:csilva, Version: 1, Date:Tue 05, July 2005,

Al usar JCalendar de (Kai Toedter) es dificil usarlo como un componente separado ya que exige estar siempre presente en la pantalla, no esta hecho como una ayuda fácil y obliga al usuario a escoger una fecha, por eso este wrapper.

Este wrapper provee un campo de texto seguido de un boton [...] que permite abrir una ventana de JCalendar con botones Ok, Cancel y Empty (para asignar la fecha en null).

Ha resultado muy util y bonito en el editor de tareas de L Gantt.

Listado 1: DateField.java

package com.csa.lib.swing;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

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

import com.toedter.calendar.JCalendar;

public class DateField extends JPanel implements ActionListener {
  private static final long serialVersionUID = 1L;
  SimpleDateFormat sdf;
  Date currentDate;
  JTextField textField;
  JButton openButton;
  JDialog helpWindow;
  JCalendar jCalendar;
  JButton bOk;
  JButton bCancel;
  JButton bClear;
  Vector actionListeners = new Vector();

  /**
   * Crea un datepicker con un formato por omision
   */
  public DateField() {
    this("dd/MM/yyyy");
  }

  /**
   * Crear un datepicker
   * 
   * @param sfmt
   *            formato para la fecha en el texto.
   */
  public DateField(String sfmt) {
    sdf = new SimpleDateFormat(sfmt);
    setLayout(new FlowLayout(0, 0, 0));
    textField = new JTextField(sfmt.length());
    openButton = new JButton("...");
    openButton.setPreferredSize(new Dimension(18, 20));
    add(textField);
    add(openButton);
    openButton.addActionListener(this);
    textField.addActionListener(this);
    textField.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() >= 2) {
          showHelpWindow();
        }
      }
    });
  }
  
  public Date getDate() {
    return currentDate;
  }

  public void setDate(Date d) {
    currentDate = d;
  }

  public JTextField getTextField() {
    return textField;
  }

  public JButton getOpenButton() {
    return openButton;
  }

  // Soporte a eventos
  public void addActionListener(ActionListener l) {
    actionListeners.add(l);
  }
  public void removeActionListener(ActionListener l) {
    actionListeners.remove(l);
  }

  protected void triggerAction() {
    for (int i = 0; i < actionListeners.size(); i++) {
      ActionListener l = (ActionListener) actionListeners.get(i);
      ActionEvent a = new ActionEvent(this, Event.ACTION_EVENT, "");
      try {
        l.actionPerformed(a);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }


  // Listeners

  public void actionPerformed(ActionEvent e) {
    // System.out.println("DatePicker.actionPerformed()");
    if (e.getSource() == openButton) {
      if (helpWindow == null)
        showHelpWindow();
      return;
    } else if (e.getSource() == bOk) {
      assignDate(jCalendar.getCalendar().getTime());
    } else if (e.getSource() == bClear) {
      assignDate(null);
    } else if (e.getSource() == textField) {
      try {
        String text = textField.getText().trim();
        if (!text.equals(""))
          assignDate(sdf.parse(text));
        else
          assignDate(null);
      } catch (ParseException e1) {
      }
    }
    hideHelpWindow();
  }

  private void assignDate(Date d) {
    currentDate = d;
    if (d != null)
      textField.setText(sdf.format(currentDate));
    else
      textField.setText("");
    triggerAction();
  }
  
  // Soporte a la ventana

  /**
   * Esconde la ventan de ayuda de seleccion de fecha.
   */
  void hideHelpWindow() {
    if ((helpWindow != null) && (helpWindow.isShowing())) {
      helpWindow.dispose();
      helpWindow = null;      
    }
  }

  /**
   * Muestra la ventana de ayuda de seleccion de fecha.
   */
  void showHelpWindow() {
    Point p = getLocationOnScreen();
    p.y += getHeight();
    helpWindow = new JDialog();
    helpWindow.setUndecorated(true);
    helpWindow.setLocation(p);
    jCalendar = new JCalendar();
    Calendar cal = Calendar.getInstance();
    if (currentDate != null)
      cal.setTime(currentDate);
    jCalendar.setCalendar(cal);
    helpWindow.getContentPane().setLayout(new BorderLayout());
    helpWindow.getContentPane().add(jCalendar, BorderLayout.CENTER);

    JPanel panel = new JPanel(new FlowLayout());
    bOk = new JButton("Ok");
    bCancel = new JButton("Cancel");
    bClear = new JButton("Clear");
    panel.add(bOk);
    panel.add(bCancel);
    panel.add(bClear);
    for (int i = 0; i < panel.getComponentCount(); i++)
      ((JButton) panel.getComponent(i)).addActionListener(this);
    helpWindow.getContentPane().add(panel, BorderLayout.SOUTH);
    helpWindow.pack();

    helpWindow.addWindowFocusListener(new WindowFocusListener() {
      public void windowGainedFocus(WindowEvent e) {
        // System.out.println("windowGainedFocus");
      }

      public void windowLostFocus(WindowEvent e) {
        // System.out.println("windowLostFocus");
        hideHelpWindow();
      }
    });
    helpWindow.setVisible(true);
  }

  /**
   * Ejemplo
   * @param args
   */
  public static void main(String[?] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(new FlowLayout());
    f.getContentPane().add(new JLabel("Fecha"));
    f.getContentPane().add(new DateField("dd/MM/yyyy"));
    f.pack();
    f.setVisible(true);
  }
}


Edit - History - Extract PDF - Extract Tree as PDF

Last Modified

Thu, Nov 19 Sat, Oct 3 Fri, Sep 25 Mon, Aug 3 Mon, Apr 27 Sat, Mar 28 Mon, Jan 19 Tue, Jan 6

Home| New Wiki