How to put a jCalendar in a cell of a JTable in Java Swing

0

I have to place a jCalendar in a cell of a table that I filled with a query from a database, but it has to be with java swing. I am trying it through a mouseclick event, I leave here the one that contains the function.

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);
    
asked by Juan Manuel Rojas Rodriguez 24.03.2018 в 18:00
source

1 answer

1

First the Main window.

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                   
 }

Then the Panel that will contain the calendar

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                   
 }

And finally this class that will listen to the events. You only have to implement the Calendar API

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) {

}
}

I hope you can guide ... !!!

    
answered by 27.03.2018 / 00:26
source