0

Tengo que colocar un jCalendar en una celda de una tabla que lleno con una consulta de una base de datos, pero tiene que ser con java swing. Lo estoy intentando por medio de un evento de mouseclick, dejo aquí el contigo que contiene la función.

int fila;
    fila = (Integer)this.jTable1.getSelectedRow();

    Date fecha = (Date)this.jTable1.getValueAt(fila, 3);

    JDateChooser jdc = new JDateChooser(fecha);

    TableColumn cb = jTable1.getColumnModel().getColumn(3);

    TableCellEditor tce = new DefaultCellEditor(jdc);
    cb.setCellEditor(tce);
3
  • No entiendo mucho tu pregunta. Supongo que en cada celda quieres desplegar una ventana emergente que contiene el calendario para seleccionar una fecha en concreto?
    – AndyC
    Commented el 25 mar. 2018 a las 0:13
  • exacto.. eso necesito... podrias ayudarme?' Commented el 26 mar. 2018 a las 17:18
  • No te preocupes. Dame un par de horas!!!!
    – AndyC
    Commented el 26 mar. 2018 a las 20:55

1 respuesta 1

1

Primero la ventana Principal.

import javax.swing.JTable;
import modelo.CalendarioTabla;


public class Ventana extends javax.swing.JFrame {

private CalendarioTabla calendarioTabla;


/**
 * Creates new form Ventana
 */
public Ventana() {
    initComponents();
    calendarioTabla = new CalendarioTabla(this);
}

public JTable getTabla() {
    return Tabla;
}

public void setTabla(JTable Tabla) {
    this.Tabla = Tabla;
}





/**
 * 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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    Tabla = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    Tabla.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {"3", "Jose", "16/11/2017"},
            {"2", "Maria", "15/03/2015"},
            {"1", "Carlos", "02/01/2018"},
            {null, null, null}
        },
        new String [] {
            "id", "usuario", "fecha"
        }
    ));
    jScrollPane1.setViewportView(Tabla);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(108, 108, 108)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(157, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(96, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(81, 81, 81))
    );

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Ventana().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JTable Tabla;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration                   
 }

Luego el Panel que contendra el calendario

import javax.swing.JTable;

public class Calendario extends javax.swing.JPanel {

/**
 * Creates new form Calendario
 */
public Calendario() {
    initComponents();

}

public JTable getFechas() {
    return Fechas;
}

public void setFechas(JTable Fechas) {
    this.Fechas = Fechas;
}





/**
 * 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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    Fechas = new javax.swing.JTable();

    setMaximumSize(new java.awt.Dimension(32767, 200));
    setPreferredSize(new java.awt.Dimension(565, 200));

    Fechas.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {"", null, null, "1", "2", "3", "4"},
            {"5", "6", "7", "8", "9", "10", "11"},
            {"12", "13", "14", "15", "16", "17", "18"},
            {"19", "20", "21", "22", "23", "24", "25"},
            {"26", "27", "28", "29", "30", "31", ""}
        },
        new String [] {
            "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo"
        }
    ) {
        Class[] types = new Class [] {
            java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
        };
        boolean[] canEdit = new boolean [] {
            false, false, false, false, false, false, false
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    jScrollPane1.setViewportView(Fechas);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 541, Short.MAX_VALUE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
            .addContainerGap())
    );
}// </editor-fold>                        


// Variables declaration - do not modify                     
private javax.swing.JTable Fechas;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration                   
 }

Y finalmente esta clase que escuchara los eventos. Solo te queda implementar la API Calendar

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;  
import java.awt.event.MouseListener;
 import javax.swing.JDialog;
 import javax.swing.JFrame;
import javax.swing.JTable;
import practicas.Calendario;
 import practicas.Ventana;

public class CalendarioTabla implements MouseListener{

private JTable Tabla, Fechas;
private JFrame Ventana;
JDialog emergente;

public CalendarioTabla(Ventana ventana) {
    this.Ventana = ventana;
    this.Tabla = ventana.getTabla();
    Tabla.addMouseListener(this);
}

public void ordenarFechas(JTable fechas){
    //Aqui debes colocar los algoritmos del api Calendar, y rellenar la tabla Fechas con los valores.

}


public void obtenerFecha(){
    Calendario calendario = new Calendario();
    this.Fechas = calendario.getFechas();
    this.Fechas.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("apretado");

            System.out.println("seleccionando Fecha: "+Fechas.getModel().getValueAt(Fechas.getSelectedRow(), Fechas.getSelectedColumn()));

            emergente.dispose();

        }

    });

    emergente = new JDialog(Ventana);
    emergente.setModal(true);
    emergente.getContentPane().add(calendario);
    emergente.setSize(calendario.getSize());
    emergente.pack();
    emergente.setVisible(true);

}

@Override
public void mouseClicked(MouseEvent e) {
    System.out.println("evento");
    System.out.println("Contenido: "+Tabla.getModel().getValueAt(Tabla.getSelectedRow(), Tabla.getSelectedColumn()));
    obtenerFecha();

}

@Override
public void mousePressed(MouseEvent e) {

}

@Override
public void mouseReleased(MouseEvent e) {

}

@Override
public void mouseEntered(MouseEvent e) {

}

@Override
public void mouseExited(MouseEvent e) {

}
}

Espero te puedas guiar...!!!

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.