CÓDIGO: Calendário Gregoriano Feito em Java

Abaixo um código feito em Java (para o Java SE 7) que manipula um calendário gregoriano simples, assumindo que se quer retornar o resultado para um campo texto de nome “txData” tipo JTextField. Esse campo pertence a uma outra janela qualquer:

[sourcecode language="java"]
import java.util.*;
import java.text.*;
public class CalendarioUI extends javax.swing.JFrame {
    private javax.swing.JTextField txData;
    
    /**
     * Creates new form CalendarioUI
     */
    public CalendarioUI() {
        initComponents();
        this.setLocationRelativeTo(null);
        this.txData = null;       
    }
    
    public void setCampoData(javax.swing.JTextField txData) {
        this.txData = txData;
        /**
         * Aqui, eu suponho que voce queira informar
         * a data selecionada do calendario a
         * um campo JTextField de uma outra janela
         */
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    private void initComponents() {
        btAnt = new javax.swing.JButton();
        txPeriodo = new javax.swing.JTextField();
        btProx = new javax.swing.JButton();
        spCalendario = new javax.swing.JScrollPane();
        tbCalendario = new javax.swing.JTable();
        btOK = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Calendário");
        setAlwaysOnTop(true);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("frCalendario");
        setResizable(false);
        setType(java.awt.Window.Type.UTILITY);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });
        btAnt.setText("«");
        btAnt.setToolTipText("");
        btAnt.setName("");
        btAnt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAntActionPerformed(evt);
            }
        });
        btAnt.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                btAntKeyReleased(evt);
            }
        });
        txPeriodo.setEditable(false);
        txPeriodo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txPeriodo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txPeriodoActionPerformed(evt);
            }
        });
        btProx.setText("»");
        btProx.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btProxActionPerformed(evt);
            }
        });
        btProx.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                btProxKeyReleased(evt);
            }
        });
        spCalendario.setBackground(new java.awt.Color(255, 255, 255));
        spCalendario.setBorder(null);
        tbCalendario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "D", "S", "T", "Q", "Q", "S", "S"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class,
                java.lang.Integer.class, java.lang.Integer.class,
                java.lang.Integer.class, java.lang.Integer.class,
                java.lang.Integer.class
            };
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tbCalendario.setCellSelectionEnabled(true);
        tbCalendario.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbCalendarioMouseClicked(evt);
            }
        });
        tbCalendario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tbCalendarioKeyReleased(evt);
            }
        });
        spCalendario.setViewportView(tbCalendario);
        btOK.setText("OK");
        btOK.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btOKMouseClicked(evt);
            }
        });
        btOK.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                btOKKeyReleased(evt);
            }
        });
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout
  (getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(15, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
   layout.createSequentialGroup()
                        .addComponent(btAnt)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE, 165,
   javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btProx)
                        .addGap(70, 70, 70))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btOK)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
   layout.createSequentialGroup()
                        .addComponent(spCalendario, javax.swing.GroupLayout.PREFERRED_SIZE,
   375, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE,                      javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btProx)
                    .addComponent(btAnt))
                .addGap(18, 18, 18)
                .addComponent(spCalendario, javax.swing.GroupLayout.PREFERRED_SIZE, 123,
  javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btOK)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pack();
    }//                        
    private String substitui () {
        String dtJDBC = this.txPeriodo.getText().toUpperCase();
        dtJDBC = dtJDBC.replaceAll("JAN", "01");
        dtJDBC = dtJDBC.replaceAll("FEV", "02");
        dtJDBC = dtJDBC.replaceAll("MAR", "03");
        dtJDBC = dtJDBC.replaceAll("ABR", "04");
        dtJDBC = dtJDBC.replaceAll("MAI", "05");
        dtJDBC = dtJDBC.replaceAll("JUN", "06");
        dtJDBC = dtJDBC.replaceAll("JUL", "07");
        dtJDBC = dtJDBC.replaceAll("AGO", "08");
        dtJDBC = dtJDBC.replaceAll("SET", "09");
        dtJDBC = dtJDBC.replaceAll("OUT", "10");
        dtJDBC = dtJDBC.replaceAll("NOV", "11");
        dtJDBC = dtJDBC.replaceAll("DEZ", "12");
        return dtJDBC;
    }
    
    private Date converte() throws Exception {
        String dtJDBC = this.substitui();
        dtJDBC = new String ("01/").concat(dtJDBC);
        DateFormat format = DateFormat.getDateInstance();
        return format.parse(dtJDBC.concat(" 0:0 AM"));
    }
    
    private void preenche(GregorianCalendar perGreg) throws Exception {
        int i, diasMes = perGreg.getActualMaximum(Calendar.DATE);
        int col = 0;
        int lin = 0;
        for (i = 0; i < 42; i++)
        {
            this.tbCalendario.setValueAt("",lin,col++);               
            if (col == 7) {
                col = 0;
                ++lin;
            }
        }              
        
        col = perGreg.get(perGreg.DAY_OF_WEEK) - 1;
        lin = 0;
        
        for (i = 0; i < diasMes; i++)
        {
            this.tbCalendario.setValueAt(String.valueOf(i + 1),lin,col++);               
            if (col == 7) {
                col = 0;
                ++lin;
            }
        }       
    }
    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
        
        SimpleDateFormat formatoPer = new
                SimpleDateFormat ("MMM/yyyy");
        Date hoje = new Date(System.currentTimeMillis());
        this.txPeriodo.setText(formatoPer.format(hoje));
        try
        {
            GregorianCalendar perGreg = new GregorianCalendar();
            perGreg.setTime(this.converte());
            this.preenche(perGreg);
        }
        catch (Exception e)
        { e.printStackTrace(); }
    }                                
    private void soma(boolean incrementa) {
        try
        {
            GregorianCalendar perGreg = new GregorianCalendar();
            perGreg.setTime(this.converte());
            if (!incrementa)
                perGreg.add(perGreg.MONTH, -1);
            else
                perGreg.add(perGreg.MONTH, 1);
            this.preenche(perGreg);
            SimpleDateFormat formatoPer = new
                    SimpleDateFormat ("MMM/yyyy");
            this.txPeriodo.setText(formatoPer.format(perGreg.getTime()));
        } catch (Exception e) {e.printStackTrace();}       
    }
    
    private void txPeriodoActionPerformed(java.awt.event.ActionEvent evt) {                                         
        
    }                                        
    private void btAntActionPerformed(java.awt.event.ActionEvent evt) {                                     
        
        this.soma(false);
    }                                    
    private void btProxActionPerformed(java.awt.event.ActionEvent evt) {                                      
        
        this.soma(true);
    }                                     
    private void tbCalendarioMouseClicked(java.awt.event.MouseEvent evt) {                                         
        
        this.gera();
    }                                        
    private void tbCalendarioKeyReleased(java.awt.event.KeyEvent evt) {                                        
        
        this.gera();
    }                                       
    private void btOKMouseClicked(java.awt.event.MouseEvent evt) {                                 
        
        this.setVisible(false);
    }                                
    private void btOKKeyReleased(java.awt.event.KeyEvent evt) {                                
        
        if (evt.getKeyCode() != evt.VK_ENTER &&
            evt.getKeyCode() != evt.VK_SPACE) return;
            this.setVisible(false);       
    }                               
    private void btAntKeyReleased(java.awt.event.KeyEvent evt) {                                 
        if (evt.getKeyCode() != evt.VK_ENTER &&
            evt.getKeyCode() != evt.VK_SPACE) return;
        this.soma(false);       
        
    }                                
    private void btProxKeyReleased(java.awt.event.KeyEvent evt) {                                  
        if (evt.getKeyCode() != evt.VK_ENTER &&
            evt.getKeyCode() != evt.VK_SPACE) return;
        this.soma(true);       
    }                                 
    private void gera() {
        int lin, col;       
        if (tbCalendario.getSelectedRowCount() > 1 ||
                tbCalendario.getSelectedColumnCount() > 1)
            tbCalendario.clearSelection();
        if (tbCalendario.getSelectedRowCount() == 0 &&
                tbCalendario.getSelectedColumnCount() == 0)
            this.txData.setText("");
       lin = tbCalendario.getSelectedRow();
       col = tbCalendario.getSelectedColumn();
       if (lin < 0 || col < 0)
           this.txData.setText("");
       String dtJDBC = (String) tbCalendario.getValueAt(lin, col);
       dtJDBC = dtJDBC.concat("/").concat(this.substitui());       
        if (dtJDBC.length() == 10)
            this.txData.setText(dtJDBC);
        else
            this.txData.setText("");
    }
    
    // Variables declaration - do not modify                    
    private javax.swing.JButton btAnt;
    private javax.swing.JButton btOK;
    private javax.swing.JButton btProx;
    private javax.swing.JScrollPane spCalendario;
    private javax.swing.JTable tbCalendario;
    private javax.swing.JTextField txPeriodo;
    // End of variables declaration                  
}
[/sourcecode]
Anúncios

Os comentários estão desativados.