ArrayIndexOutOfBoundsException with JTable.setValueAt()

Hi everybody.
I can't understand what happens with my code. When I try to call the JTable.setValueAt method, an ArrayIndexOutOfBoundsException is thrown. Here is my code:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import frontOffice.applets.AppletResultats;
import java.util.*;
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author unascribed
* @version 1.0
public class VueResultats extends JFrame {
  private AppletResultats applet;
  private JTable tableau = new JTable(new DefaultTableModel(){
      public boolean isCellEditable(int row, int column) {
        return false;
  private JScrollPane scrollPane = new JScrollPane(tableau);
  public VueResultats(AppletResultats applet) {
    super("R?sultats enregistr?s");
    this.applet = applet;
    this.getContentPane().setLayout(new FlowLayout());
    this.setContentPane(this.scrollPane);
    scrollPane.setViewportView(tableau);
    scrollPane.setPreferredSize(new Dimension(400, 100));
    String codebaseHost = applet.getCodebasesHost();
    tableau.getTableHeader().setDefaultRenderer(new HeaderRenderer(codebaseHost));
    TableColumn colonneAnnee = new TableColumn();
    colonneAnnee.setHeaderValue("Ann?e");
    tableau.addColumn(colonneAnnee);
    TableColumn colonneCA = new TableColumn();
    colonneCA.setHeaderValue("Chiffre d'affaires");
    tableau.addColumn(colonneCA);
    TableColumn colonneBen = new TableColumn();
    colonneBen.setHeaderValue("B?n?fice");
    tableau.addColumn(colonneBen);
    TableColumn colonneConc = new TableColumn();
    colonneConc.setHeaderValue("Concerne");
    tableau.addColumn(colonneConc);
    for(Enumeration e = tableau.getColumnModel().getColumns(); e.hasMoreElements();) {
        TableColumn column = (TableColumn) e.nextElement();
        column.setCellRenderer(new MyCellRenderer());
        System.out.println(column.getClass());
    this.pack();
    this.setResizable(false);
    System.out.println("Vue cr??e " + tableau.getColumnCount() + "colonnes");
    this.update();
  public void update() {
    DefaultTableModel model = (DefaultTableModel) this.tableau.getModel();
    Vector resultats = this.applet.getResultats();
    model.setRowCount(resultats.size());
    System.out.println("Rowcount: " + resultats.size());
    int i = 0;
    for(Enumeration e = resultats.elements(); e.hasMoreElements(); i++) {
      Resultat resultat = (Resultat) e.nextElement();
      tableau.setValueAt(resultat.annee(), i, 1);            // Here occurs the exception !!!!!!!!!!!!
      tableau.setValueAt(resultat.chiffreA(), i, 2);
      tableau.setValueAt(resultat.benefice(), i, 3);
      tableau.setValueAt(resultat.concerne() ? "Votre entreprise" : "Votre groupe", i, 4);
  private class MyCellRenderer extends JLabel implements TableCellRenderer {
        public MyCellRenderer() {
            System.out.println("CellRenderer cr??");
        private MyCellRenderer(boolean isSelected) {
            if(isSelected) this.setBackground(new Color(0x49aba6));
            else this.setBackground(Color.WHITE);
            this.setHorizontalTextPosition(SwingConstants.CENTER);
            this.setVerticalTextPosition(SwingConstants.CENTER);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            MyCellRenderer renderer = new MyCellRenderer(isSelected);
            renderer.setText(value.toString());
            return renderer;
  public static void main(String args[]) {
    new VueResultats(new AppletResultats()).setVisible(true);
}Can anyone explain to me why this exception ??
Notice I call the DefaultTableModel.setRowCount() method before setValueAt().
Thank's in advance for any reply.

Really no idea ?????
Please help !!!! I can't understand how JTables work.

Similar Messages

  • Problem hotspot with Jtable

    i am sorry may english, my English is not very good, my natural language is Spanish.
    I am using jtable, i beginning it with elements null and i fill it after. But when i am going to fill it i get the next error
    Java VM: Java HotSpot(TM) Client VM (1.4.0-b92 mixed mode)
    # Error ID: 434F444523414348450E43505000BE
    # Problematic Thread: prio=7 tid=0x0AB83010 nid=0x7f8 runnable
    but i use -server for running, then i don`t get the error.
    somebory can help me.

    here is the complete class.
    I call first the method
    iniciaTablaVector(
    boolean puede_editar,
    boolean puede_sortear,
    boolean puede_seleccionar)
    after i get the data from the database and add them into the vectors i call
    the method
    asignaDatosTabla(java.util.Vector vector_campos_usar,
    java.util.Vector vector_campos_usar_i,
    java.util.Vector vector_datos,
    java.util.Vector vector_datos_campos)
    package version01;
    * TITULOS: Programas Boca
    * DESCRIPCION Programas Generales
    * DERECHO RESERVADO Derechos reservado 2001
    * COMPANIA Sistemas Boca
    * @AUTORES Jos� Alberto Felipe y Jos� Luis Marte
    * @VERSION 1.0
    public class ManejoTablaVector02 //extends javax.swing.JTable
    javax.swing.JTable vista_tabla;
    miModeloTabla mimodelotabla;
    private boolean DEBUG = true;
    private boolean PUEDE_SEL_COLUMNA = false;
    private boolean PUEDE_SEL_FILA = true;
    private int fila_sel;
    java.awt.Container frame_usar;
    ManejoParametros manejoparametros;
    java.util.Vector vector_columnas, vector_campos_usar,vector_campos_usar_i;
    java.util.Vector vector_datos,vector_datos_campos ;
    javax.swing.JComponent[] campos;
    java.util.Vector vector_campos;
    java.util.TreeMap map_campos;
    ManejoPantalla manejopantalla;
    javax.swing.ListSelectionModel modelo_fila_sel;
    boolean puede_editar;
    boolean puede_sortear;
    boolean puede_seleccionar;
    //Object[] valores_largo;
    //Class[] clase_columnas;
    java.util.Vector valores_largo;
    java.util.Vector clase_columnas;
    public ManejoTablaVector02(java.awt.Container frame_usar,
    ManejoParametros manejoparametros,
    // java.util.Vector vector_datos,
    // java.util.Vector vector_datos_campos,
    // java.util.Vector vector_campos_usar,
    // java.util.Vector vector_campos_usar_i,
    javax.swing.JComponent[] campos,
    java.util.Vector vector_campos,
    java.util.TreeMap map_campos)
    this.frame_usar = frame_usar;
    this.manejoparametros = manejoparametros;
    /* this.vector_campos_usar = vector_campos_usar;
    this.vector_campos_usar_i = vector_campos_usar_i;
    if (manejoparametros.datos_leidos_tablas == null)
    manejoparametros.datos_leidos_tablas = new java.util.Vector();
    if (manejoparametros.datos_leidos_campos == null)
    manejoparametros.datos_leidos_campos = new java.util.Vector();
    // this.vector_datos =
    // manejoparametros.datos_leidos_tablas;
    // this.vector_datos_campos =
    // manejoparametros.datos_leidos_campos;
    this.campos = campos;
    this.vector_campos = vector_campos;
    this.map_campos = map_campos;
    // obtieneEncabezadoTabla();
    // asignaDatosCamposIniciales();
    // obtieneColumnasTabla();
    //public javax.swing.JTable iniciaTablaVector(
    public void iniciaTablaVector(
    boolean puede_editar,
    boolean puede_sortear,
    boolean puede_seleccionar)
    this.puede_editar = puede_editar;
    this.puede_sortear = puede_sortear;
    this.puede_seleccionar = puede_seleccionar;
    // Instead of making the table display the data as it would normally with:
    // JTable vista_tabla = new JTable(dataModel);
    // Add a sorter, by using the following three lines instead of the one above.
    //va TableSorter sorter = new TableSorter(dataModel);
    vista_tabla= new javax.swing.JTable();
    /*Desabilita el manejo de columna de la tabla para manejarlo manual*/
    vista_tabla.setAutoCreateColumnsFromModel(false);
    manejopantalla = new ManejoPantalla();
    obtieneColumnasTabla();
    this.vector_datos =
    manejoparametros.datos_leidos_tablas;
    this.vector_datos_campos =
    manejoparametros.datos_leidos_campos;
    iniciaVectorDatos();
    mimodelotabla = new miModeloTabla();
    /* mimodelotabla = new miModeloTabla(
    manejoparametros,
    vector_columnas,
    vector_datos,
    vector_datos_campos,
    campos,
    vector_campos,
    map_campos,
    manejopantalla);
    vista_tabla.setModel(mimodelotabla);
    configuraColumna(vista_tabla);
    asignaEscuchadores();
    // asignaAnchoColumnas(vista_tabla, mimodelotabla);
    // asignaEscuchadores();
    // Crear a modelo de tabla.
    class miModeloTabla extends javax.swing.table.AbstractTableModel
    java.util.Vector vector_columnas;
    java.util.Vector vector_campos_usar,
    vector_campos_usar_i;
    java.util.Vector vector_datos,vector_datos_campos;
    javax.swing.JComponent[] campos;
    java.util.Vector vector_campos;
    java.util.TreeMap map_campos;
    ManejoPantalla manejopantalla;
    ManejoParametros manejoparametros;
    public miModeloTabla(ManejoParametros manejoparametros,
    java.util.Vector vector_columnas,
    java.util.Vector vector_datos,
    java.util.Vector vector_datos_campos,
    javax.swing.JComponent[] campos,
    java.util.Vector vector_campos,
    java.util.TreeMap map_campos,
    ManejoPantalla manejopantalla)
    this.manejoparametros = manejoparametros;
    this.vector_columnas = vector_columnas;
    // this.vector_campos_usar = vector_campos_usar;
    // this.vector_campos_usar_i = vector_campos_usar_i;
    this.vector_datos = vector_datos;
    this.vector_datos_campos = vector_datos_campos;
    this.campos = campos;
    this.vector_campos = vector_campos;
    this.map_campos = map_campos;
    this.manejopantalla = manejopantalla;
    // javax.swing.table.TableModel dataModel =
    // new javax.swing.table.AbstractTableModel()
    // These methods always need to be implemented.
    /* Para asignar los anchos de la columna
    Se pueden asignar por el la columna que tenga mas tama�o
    public final Object[] valores_largo = {"Angela", "Andrews",
    "esto es mas que una prueba","prueba",
    "prueba","prueba","prueba","prueba","N"};*/
    class miModeloTabla extends javax.swing.table.AbstractTableModel
    public int getColumnCount()
    return vector_columnas.size();
    public int getRowCount()
    return vector_datos==null ? 0 : vector_datos.size();
    public Object getValueAt(int row, int col)
    int total_columna = ((java.util.Vector)
    (vector_datos.elementAt(row))).size() + 1;
    if (total_columna > col)
    return ((java.util.Vector)
    (vector_datos.elementAt(row))).elementAt(col);
    }else
    return null;
    // The default implementations of these methods in
    // AbstractTableModel would work, but we can refine them.
    public String getColumnName(int columna)
    String indice_str =(String)
    ((Object[])vector_columnas.elementAt(columna))[1];
    int indice_vector_campos = Integer.parseInt(indice_str);
    return (String)((Object[])
    vector_campos.elementAt(indice_vector_campos))[3];
    public Class getColumnClass(int columna)
    // {return getValueAt(0,columna).getClass();}
    String indice_str =(String)
    ((Object[])vector_columnas.elementAt(columna))[1];
    int indice_vector_campos = Integer.parseInt(indice_str);
    return (Class)obtieneTipoColumna(
    (String)((Object[])
    vector_campos.elementAt(indice_vector_campos))[29]);
    public boolean isCellEditable(int fila, int columna)
    if (puede_editar)
    String indice_str =(String)
    ((Object[])vector_columnas.elementAt(columna))[1];
    int indice_vector_campos = Integer.parseInt(indice_str);
    if (((String)
    ((Object[])
    vector_campos.elementAt(
    indice_vector_campos))[18]).equals("true"))
    return true;
    else
    return false;
    }else return false;
    /* public void setValueAt(Object aValue, int fila, int columna)
    if (puede_editar)
    ((java.util.Vector)
    (vector_datos.elementAt(fila))).elementAt(columna) = aValue;
    fireTableCellUpdated(fila, columna);
    // public static void main(String[] args) {
    // new TableExample3();
    //final de clase
    public void asignaDatosTabla(java.util.Vector vector_campos_usar,
    java.util.Vector vector_campos_usar_i,
    java.util.Vector vector_datos,
    java.util.Vector vector_datos_campos)
    this.vector_campos_usar = vector_campos_usar;
    this.vector_campos_usar_i = vector_campos_usar_i;
    this.vector_datos = vector_datos;
    this.vector_datos_campos = vector_datos_campos;
    // asignaDatosCamposIniciales();
    // mimodelotabla.fireTableDataChanged();
    // configuraColumna(vista_tabla);
    // javax.swing.table.TableModel modelo = vista_tabla.getModel();
    mimodelotabla.fireTableDataChanged();
    // vista_tabla.repaint();
    vista_tabla.requestFocus();
    javax.swing.ListSelectionModel listseleccion = vista_tabla.getSelectionModel();
    listseleccion.setLeadSelectionIndex(0);
    vista_tabla.setSelectionModel(listseleccion);
    //javax.swing.ListSelectionModel lsm =
    // (javax.swing.ListSelectionModel)e.getSource();
    // asignaEscuchadores();
    public void iniciaVectorDatos()
    java.util.Vector vectornulo;
    manejoparametros.datos_leidos_tablas.clear();
    if (!vector_columnas.isEmpty())
    for(int i=0;i<30;i++)
    vectornulo = new java.util.Vector();
    for (int j = 0;j<vector_columnas.size();j++)
    vectornulo.addElement(null);
    vector_datos.addElement(vectornulo);
    private void asignaEscuchadores()
    vista_tabla.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    if (puede_seleccionar) { // true by default
    modelo_fila_sel = vista_tabla.getSelectionModel();
    modelo_fila_sel.addListSelectionListener(
    new javax.swing.event.ListSelectionListener() {    
    public void valueChanged(
    javax.swing.event.ListSelectionEvent e)
    javax.swing.ListSelectionModel lsm =
    (javax.swing.ListSelectionModel)e.getSource();
    int fila_sel = lsm.getMinSelectionIndex();
    // DEBO BUSCAR UNA FORMA DE DETERMINAR SI EL VECTOR DE CAMPOS TIENE DATOS
    if (!vector_datos_campos.isEmpty())// !=null)
    manejopantalla.asignaDatosPantalla(
    (java.util.TreeMap)
    vector_datos_campos.elementAt(fila_sel),
    campos,
    vector_campos);
    /*Aqui funcionan para cambiar los campos de arriba de la forma
    que esta abajo
    ((javax.swing.JTextField)campos[0]).setText(
    (String)vista_tabla.getValueAt(fila_sel,0));
    ((javax.swing.JTextField)campos[1]).setText((String)vista_tabla.getValueAt(fila_sel,1));
    //v if (lsm.isSelectionEmpty()) {
    //v System.out.println("No rows are selected.");
    //v } else {
    //v int selectedRow = lsm.getMinSelectionIndex();
    //v System.out.println("Row " + selectedRow
    //v + " is now selected.");
    //v }
    } else {
    vista_tabla.setRowSelectionAllowed(false);
    vista_tabla.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent e) {
    fila_sel = vista_tabla.getSelectedRow();
    if (e.getClickCount() ==2)
    asignaDatosSeleccionados(fila_sel);
    salirPrograma();
    // System.out.println("FILA SEL --> " + fila_sel);
    /*Aqui va chequeo de seleccion
    ((javax.swing.JTextField)campos[0]).setText((String)vista_tabla.getValueAt(fila_sel,0));
    ((javax.swing.JTextField)campos[1]).setText((String)vista_tabla.getValueAt(fila_sel,1));
    vista_tabla.addKeyListener(new java.awt.event.KeyAdapter()
    public void keyPressed(java.awt.event.KeyEvent e)
    // char c = e.getKeyChar();
    int keycode = e.getKeyCode();
    if (keycode == 10)
    fila_sel = vista_tabla.getSelectedRow();
    asignaDatosSeleccionados(fila_sel);
    salirPrograma();
    // System.out.println("FILA SEL --> " + fila_sel);
    public void configuraColumna(javax.swing.JTable tabla)
    int tamano;
    for (int i=0;i<vector_columnas.size();i++)
    String indice_str =(String)
    ((Object[])vector_columnas.elementAt(i))[1];
    int indice_vector_campos = Integer.parseInt(indice_str);
    /*Aqui se asigna en render de cada celda esto permite
    fijar el font de las celdas, el borde, fijar, estado
    colores,etc. Debo crear uno propio para tener mas control*/
    javax.swing.table.DefaultTableCellRenderer
    renderer = new javax.swing.table.DefaultTableCellRenderer();
    /*Debo agregar un campo en el archivo de configuracion para
    saber como voy alinear el campo (derecha,izquierda,centro)*/
    renderer.setHorizontalAlignment(renderer.LEFT);
    //javax.swing.JLabel.LEFTNTER_ALIGNMENT);
    // renderer.setText((String)((Object[])
    // vector_campos.elementAt(
    // indice_vector_campos))[3]);
    if (!UtilitariosGenerales.isCampoBlanco(((String)((Object[])
    vector_campos.elementAt(
    indice_vector_campos))[26])))
    tamano = Integer.parseInt(((String)((Object[])
    vector_campos.elementAt(
    indice_vector_campos))[26]));
    }else
    tamano = 10;
    /*Debo crear mi propio tipo de editor de celdas, para formatear
    los datos debo llamarlo aqui, ahi tomo en cuenta el tipo de
    datos que voy a usar (JCombo, JcheckBox, JTextField)*/
    javax.swing.table.TableCellEditor editor;
    if (
    /* ((String)((Object[])
    vector_campos.elementAt(indice_vector_campos))[2]).equals("JCheckBox")
    ((String)((Object[])
    vector_campos.elementAt(indice_vector_campos))[29]).equals("Boolean")
    javax.swing.JCheckBox checkbox = new javax.swing.JCheckBox();
    editor = new javax.swing.DefaultCellEditor(checkbox);
    else
    javax.swing.JTextField jtextfield = new javax.swing.JTextField();
    editor = new javax.swing.DefaultCellEditor(jtextfield);
    javax.swing.table.TableColumn columna = new
    javax.swing.table.TableColumn(
    i,tamano,renderer,editor);
    tabla.addColumn(columna);
    public void obtieneColumnasTabla()
    vector_columnas = new java.util.Vector();
    int indice_vector;
    String[] informacion_columna;
    for (int i=0;i<vector_campos.size();i++)
    if (!
    ((String)((Object[])vector_campos.elementAt(i))[2]).equals(
    "JTable"))
    continue;
    informacion_columna = new String[2];
    informacion_columna[0] = (String)((Object[])vector_campos.elementAt(i))[3];
    informacion_columna[1] = String.valueOf(i);
    vector_columnas.addElement(informacion_columna);
    public Object obtieneTipoColumna(String tipo_columna)
    String[] arreglo_tipo = {"String","Long","Integer","Double","Boolean"};
    int i = java.util.Arrays.binarySearch(arreglo_tipo,tipo_columna);
    switch (i)
    case 0:
    return String.class;
    case 1:
    return Long.class;
    case 2:
    return Integer.class;
    case 3:
    return Double.class;
    case 4:
    return Boolean.class;
    default:
    return String.class;
    class FormattedCellRenderer extends javax.swing.table.DefaultTableCellRenderer
         protected java.text.Format m_format;
         public FormattedCellRenderer(java.text.Format format) {
              m_format = format;
         public java.awt.Component getTableCellRendererComponent(
    javax.swing.JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              return super.getTableCellRendererComponent(table,
                   value==null ? null : m_format.format(value),
                   isSelected, hasFocus, nRow, nCol);
    class FormattedCellEditor extends javax.swing.DefaultCellEditor
         public FormattedCellEditor(final javax.swing.JFormattedTextField
                   formattedTextField) {
              super(formattedTextField);
    System.out.println(delegate);
              formattedTextField.removeActionListener(delegate);
              delegate = new EditorDelegate() {
                   public void setValue(Object value) {
                        formattedTextField.setValue(value);
                   public Object getCellEditorValue() {
                        return formattedTextField.getValue();
              formattedTextField.addActionListener(delegate);
              formattedTextField.setBorder(null);
    public void asignaDatosSeleccionados(int fila)
    if (fila >=0 && fila < vector_datos.size())
    manejoparametros.isSeleccionada = true;
    java.util.TreeMap map_datos_sel = new java.util.TreeMap();
    int indice_vector;
    int total_tabla=-1;
    int total_campos = -1;
    for (int i=0;i<vector_campos_usar.size();i++)
    // String[] arreglo_campo_usar = new String[2];
    // arreglo_campo_usar = (String[])vector_campos_usar.elementAt(i);
    // indice_vector = Integer.parseInt(arreglo_campo_usar[0]);
    /*AQUI DEBO CLASIFICAR SI ES FIJO O ES DE LA TABLA*/
    if (!
    ((String)((Object[])vector_campos_usar_i.elementAt(i))[2]).equals(
    "JTable"))
    if (!UtilitariosGenerales.isCampoBlanco(
    ((String)((Object[])vector_campos_usar_i.elementAt(i))[28]) ) &&
    !((String)((Object[])vector_campos_usar_i.elementAt(i))[40]).equals(
    "true"))
    if (!map_datos_sel.containsKey(
    ((Object[])vector_campos_usar_i.elementAt(i))[28]))
    total_campos++;
    Object valores = ((java.util.TreeMap)
    vector_datos_campos.elementAt(fila)).get(
    ((Object[])vector_campos_usar_i.elementAt(
    i))[28]);
    map_datos_sel.put( ((Object[])vector_campos_usar_i.elementAt(i))[28],
    valores);
    // ((java.util.Vector)
    // vector_datos_campos.elementAt(fila)).elementAt(total_campos) );
    // continue;
    for (int i =0;i<vector_campos.size();i++)
    if (
    ((String)((Object[])vector_campos.elementAt(i))[2]).equals(
    "JTable"))
    total_tabla++;
    if (!UtilitariosGenerales.isCampoBlanco(
    ((String)((Object[])vector_campos.elementAt(i))[28]) ))
    if (!map_datos_sel.containsKey(
    ((Object[])vector_campos.elementAt(i))[28]))
    map_datos_sel.put( ((Object[])vector_campos.elementAt(i))[28],
    ((java.util.Vector)
    vector_datos.elementAt(fila)).elementAt(i) );
    manejoparametros.fila_seleccionada = fila;
    manejoparametros.map_datos_seleccionados = map_datos_sel;
    public void obtieneDatosSeleccionados_ant(int fila)
    if (fila >=0 && fila < vector_datos.size())
    manejoparametros.isSeleccionada = true;
    java.util.TreeMap map_datos_sel = new java.util.TreeMap();
    int indice_vector;
    int total_tabla=-1;
    for (int i=0;i<vector_campos_usar.size();i++)
    // String[] arreglo_campo_usar = new String[2];
    // arreglo_campo_usar = (String[])vector_campos_usar.elementAt(i);
    // indice_vector = Integer.parseInt(arreglo_campo_usar[0]);
    /*AQUI DEBO CLASIFICAR SI ES FIJO O ES DE LA TABLA*/
    if (!
    ((String)((Object[])vector_campos_usar_i.elementAt(i))[2]).equals(
    "JTable"))
    continue;
    else
    total_tabla++;
    if (!UtilitariosGenerales.isCampoBlanco(
    ((String)((Object[])vector_campos_usar_i.elementAt(i))[28]) ))
    if (!map_datos_sel.containsKey(
    ((Object[])vector_campos_usar_i.elementAt(i))[28]))
    map_datos_sel.put( ((Object[])vector_campos_usar_i.elementAt(i))[28],
    ((java.util.Vector)
    vector_datos.elementAt(fila)).elementAt(total_tabla) );
    int total_campos = -1;
    for (int i=0;i<vector_campos.size();i++)
    if (!UtilitariosGenerales.isCampoBlanco(
    ((String)((Object[])vector_campos.elementAt(i))[28]) ) &&
    !((String)((Object[])vector_campos.elementAt(i))[2]).equals(
    "JEncadena"))
    if (!map_datos_sel.containsKey(
    ((Object[])vector_campos.elementAt(i))[28]))
    total_campos++;
    String valores = (String)((java.util.TreeMap)
    vector_datos_campos.elementAt(fila)).get(
    ((Object[])vector_campos.elementAt(
    i))[28]);
    map_datos_sel.put( ((Object[])vector_campos.elementAt(i))[28],
    valores);
    // ((java.util.Vector)
    // vector_datos_campos.elementAt(fila)).elementAt(total_campos) );
    manejoparametros.fila_seleccionada = fila;
    manejoparametros.map_datos_seleccionados = map_datos_sel;
    public void salirPrograma()
    try
    if (frame_usar instanceof javax.swing.JDialog)
    ((javax.swing.JDialog)frame_usar).setName("botones");
    ((javax.swing.JDialog)frame_usar).dispose();
    }else
    ((javax.swing.JFrame)frame_usar).setName("botones");
    ((javax.swing.JFrame)frame_usar).dispose();
    }catch (Exception ex)
    System.out.println(ex.toString());
    }

  • Mouselistner is not working with jtable in the browser

    Hi
    I am having a problem with jTable.
    I added a mouselistener to table header to sort table but when i run that applet from my netbean ide it works fine but when i run that applet in my browser it doesn't work, i have tested, its not even generate mouseclick event .Please help me guys.
    I call this function after calling initComponents() method of JApplet.
    public void setTableAction()
    //set mouselistener to sort table on click of table header
    final JTableHeader head= jTable1.getTableHeader();
    head.addMouseListener(new java.awt.event.MouseAdapter()
    public void mouseClicked(java.awt.event.MouseEvent evt)
    Vector data= ((DefaultTableModel)jTable1.getModel ()).getDataVector();
    sortTable(data, head.columnAtPoint(evt.getPoint()));
    //set action map to change the default action performed for enter key pressed
    InputMap imap = jTable1.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    KeyStroke tabKey = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
    final Action oldAction= jTable1.getActionMap().get(imap.get(tabKey)); // get map to set enter key.
    imap.put(enterKey, "enter"); // set enter key
    Action newAction = new AbstractAction(){
    public void actionPerformed(ActionEvent e) {
    oldAction.actionPerformed(e);
    JTable table= (JTable)e.getSource();
    table.changeSelection(0,0,false,false);
    if(table.isCellEditable(0,0))
    String sTemp= (String)table.getValueAt(0,0);
    if(sTemp.length()>0) {
    if(bRenewItem)
    retrieveRcodeDetails("",sTemp);
    else
    processRCodeDetails(sTemp, e);
    }else
    table.editCellAt(0,0);
    jTable1.getActionMap().put("enter", newAction);
    jTable1.setPreferredScrollableViewportSize(jTable1.getPreferredSize());
    }

    Hi,
    I also am using the Bépo layout with an encrypted drive and encountered the same problem: the Return key does not work.
    It seems to work fine if you use the fr-bepo-latin9 keymap.
    # /etc/vconsole.conf
    KEYMAP=fr-bepo-latin9
    But I also looked at the files /usr/share/kbd/keymaps/i386/bepo/fr-bepo.map.gz and /usr/share/kbd/keymaps/i386/bepo/fr-bepo-latin9.map.gz (you can open gzipped files in vim directly). fr-bepo-latin9.map.gz defines keycode 28 (Return) but fr-bepo.map.gz does not.
    I modified fr-bepo.map.gz:
    # vim /usr/share/kbd/keymaps/i386/bepo/fr-bepo.map.gz # Append that line : "keycode 28 = Return".
    # mkinitcpio -p linux # Rebuild the initramfs.
    The Return key now works, but the Backspace (14, "Delete") and Shift (54) keys don’t work. I found that both the cf.map.gz (french canadian layout) and fr-bepo-latin9.map.gz files define those keycodes as well as other non-printing keys so I copied the following lines from fr-bepo-latin9.map.gz to fr-bepo.map.gz:
    keycode 1 = Escape Escape
    keycode 14 = Delete Delete
    keycode 15 = Tab Tab
    keycode 28 = Return
    keycode 29 = Control
    keycode 42 = Shift
    keycode 54 = Shift
    keycode 56 = Alt
    keycode 58 = Caps_Lock
    keycode 97 = Control
    It works! Don’t forget to rebuild the initramfs after you change the keymap file.
    # mkinitcpio -p linux
    I will send a message to the kbd and bépo projects mailing lists and report back.

  • Selection Problem with JTable

    Hello,
    i have a selection problem with JTable. I want to allow only single cell selection and additionally limit the selection to the first column.
    I preffered the style from MS Outlook Express where you can select the email accounts to edit.
    It is a table like this:
    Account name  |   Type  |   ...
    --------------|---------|---------------------
    Hotmail       |   POP3  |
    GMX           |   IMAP  |The selection should be only avaibable at 'Hotmail' or 'GMX' - not at 'POP3', 'IMAP' or as complete row selection.
    Please help me!
    Thanks.
    Warlock

    Maybe this will helpimport java.awt.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One", "Two"};
        String[][] data = {{"R1-C1", "R1-C2"}, {"R2-C1", "R2-C2"}};
        JTable jt = new JTable(data, head);
        jt.getColumnModel().setSelectionModel(new MyTableSelectionModel());
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        jt.setCellSelectionEnabled(true);
        jt.setRowSelectionAllowed(false);
        jt.setColumnSelectionAllowed(false);
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] arghs) { new Test3(); }
    class MyTableSelectionModel extends DefaultListSelectionModel {
      public void setSelectionInterval(int index0, int index1) {
        super.setSelectionInterval(0, 0);
    }

  • Any body please can solve my problem that iam facing with JTable

    Dear sir,
    Iam doing an educational product using Swing as front end in that
    iam using JTables. And back end iam using sqlserver. With jtable iam
    facing very serious problem the problem is actually iam entering the values
    in all the columns after that iam pressing the save button its not
    saving but if i click on any of the columns and try to save its saving.
    please anybody can solve my problem.Please if a piece of code is there ill
    be very thankful to you. my mailid is [email protected]
    regards
    surya

    The problem is, the cellEditor does not know that editing has stopped and therefore has not updated the model (where the data actually resides). When you click off the cell to another cell, the first cell knows it must be done editing because you are leaving it. If you click a button (or anything other than another cell), the cell being edited has no knowledge of this. You need to call stopCellEditing() on the cell editor and your problem will be solved. To do this, put the following method into your code and call it when you click the button to clear, save or whatever you need to do.
    public void ceaseEditing() {    int row = this.getEditingRow();
      int col = this.getEditingColumn();
      if (row != -1 && col != -1)
        this.getCellEditor(row,col).stopCellEditing(); 
      }Hope this helped...

  • Plz tell me how to use JSpinner with JTable

    I have retrieve records from database but as the number of records(rows) are more than 1000 , i want to use JSpinner with JTable . plz solve my problem by giving the appropriate code for the same.

    hi
    check this links
    http://www.exampledepot.com/egs/javax.swing.table/CustRend.html
    http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    hope this will help you.. this explains exactly what you want.
    regards
    Aniruddha

  • JComboBox With JTable as Editor

    Hi everybody
    I'm working with JTable and having a ComboBox as first CellEditor. for that purpose i used following code
            cmbFeeType.setModel(new javax.swing.DefaultComboBoxModel(DefaultFee.FeeTypeItemList()));       
            DefaultCellEditor DCEFeeType = new DefaultCellEditor(cmbFeeType);
            DCEFeeType.setClickCountToStart(2);here DefaultFee.FeeTypeItemList is a vector returns array. This is working fine except that the ComboBox remains visible till I dobule clik on a column for editing. Then It becomes invisible and works fine.
    my JComboBox is a seperate Control on a JFrame I do not want to use
    Class FeeTypeEditor extends JComboBox implements TableCellEditoras a ComboBox editor for JTable
    Please Help Me.

    Hi
    I am giving u a sample code which simulate the error
    * TestJTable.java
    * Created on August 5, 2008, 11:05 AM
    package TestJTable;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableColumn;
    * @author  yogi
    public class TestJTable extends javax.swing.JFrame {
        /** Creates new form TestJTable */
        public TestJTable() {
            initComponents();
            DefaultCellEditor ColumnEditor = new DefaultCellEditor(jComboBox1);
            ColumnEditor.setClickCountToStart(2);
            TableColumn column = jTable1.getColumnModel().getColumn(0);
            column.setCellEditor(ColumnEditor);       
        /** 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.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            jComboBox1 = new javax.swing.JComboBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            getContentPane().setLayout(null);
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane1.setViewportView(jTable1);
            getContentPane().add(jScrollPane1);
            jScrollPane1.setBounds(10, 10, 340, 180);
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
            getContentPane().add(jComboBox1);
            jComboBox1.setBounds(180, 220, 120, 20);
            pack();
        }// </editor-fold>//GEN-END:initComponents
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    TestJTable TJTable = new TestJTable();
                    TJTable.setExtendedState(MAXIMIZED_BOTH);               
                    TJTable.setVisible(true);
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration//GEN-END:variables
    }Above code is generated by Netbeans IDE 6.0
    My promblem is that when you run the code the combobox JComboBox1 remains visible till i starts to edit the Table after once started editing it disappears.
    I want to avoid this
    thanks in advance

  • Issue with JTable

    Hi,
    I have a issue with JTable. I am reading an array and populating the cells in the JTable. After editing the cell values, on clicking a button, I update the value in to an array. The probelm is that after editing the value in the cell, if I don't use tab or enter key and move the focus away from the cell, I dont get the updated value when using the getValueAt method. Pleease let me know if there is any workaround for this behaviour.
    Thanks,
    Baskar N

    Just so you understand why that code snippit works, you have to stop or cancel editing before you can get the updated value of a cell.

  • Where can I find a JClient demo with JTable ?

    Hi,
    Where can I find a good JClient demo with JTable and Bc4J?
    Thanks
    Friedhold

    Friedhold,
    there exist a JTable example on otn.oracle.com/products/jdev
    For example ther exists a component binding demo
    http://otn.oracle.com/sample_code/products/jdev/jclient/JClientBindingDemo.zip
    that also shows a table
    and a sorter demo that shows how to sort JTables with JClient
    http://otn.oracle.com/sample_code/products/jdev/jclient/TableSorter.zip
    Finally, a demo that shows how to replace a table cell by a combo box using the table cell renderer
    http://otn.oracle.com/sample_code/products/jdev/jclient/JTableCombo.zip
    Frank

  • Help please with Jtable

    HI
    I'm having problems
    I have a frame that has a textField, button, label.
    The button is used to diplay the Jtable which has the resultSet.
    My query is:
    String query = "SELECT personID, firstName, surname FROM Person where firstName = '" + jTxtTest.getText() + "'";
    If I enter Gita in the textField and press the button it should display the personID, firstName, surname where firtsname = Gita
    in the Jtable and also display Gita in the label.
    But it only display Gita in the Label but noting in the Jtable.
    What am i doing wrong?????
    public class Frame1 extends JFrame {
    JPanel contentPane;
    BorderLayout borderLayout1 = new BorderLayout();;
              String driver="sun.jdbc.odbc.JdbcOdbcDriver";
              String url="jdbc:odbc:myDatabase";
              String tempname = "";
              int tempcnt;
              JTabbedPane tabbedPane = new JTabbedPane();
              Object[] data = new Object[20];
              DefaultTableModel defaulttablemodel = new DefaultTableModel();
              JTable jtable = new JTable(defaulttablemodel);
    JPanel p1 = new JPanel();
    JTabbedPane jTabbedPane1 = new JTabbedPane();
    JPanel jPanel1 = new JPanel();
    JTextField jTxtTest = new JTextField();
    JButton jButton1 = new JButton();
    JLabel jLabel1 = new JLabel();
    /**Construct the frame*/
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception {
    setup();
    contentPane = (JPanel) this.getContentPane();
    this.setSize(new Dimension(554, 532));
    this.setTitle("Frame Title");
    jPanel1.setLayout(null);
    jTxtTest.setBounds(new Rectangle(53, 20, 208, 33));
    jButton1.setText("jButton1");
    jButton1.setBounds(new Rectangle(314, 19, 130, 36));
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jButton1_actionPerformed(e);
    jLabel1.setBounds(new Rectangle(462, 23, 82, 20));
    contentPane.add(jTabbedPane1, BorderLayout.CENTER);
    jTabbedPane1.add(jPanel1, "jPanel1");
    jPanel1.add(jTxtTest, null);
    jPanel1.add(jButton1, null);
    jPanel1.add(jLabel1, null);
    void setup()
                   setupMenuBar();
                   showpane1();
                   //contentPane.add(tabbedPane, BorderLayout.CENTER);
              //------------------------------------------------------------ End setup -----------------
              //============================================================ Start setupMenuBar ========
              void setupMenuBar()
                   MenuBar menuBar = new MenuBar();
                   Menu fileMenu = new Menu("File");
                             MenuItem fileExit = new MenuItem("Exit");
                                  fileExit.addActionListener(new MenuItemHandler());
                                  fileMenu.add(fileExit);
    MenuItem filePrev = new MenuItem("Preview");
                                  filePrev.addActionListener(new MenuItemHandler());
                                  fileMenu.add(filePrev);
                             menuBar.add(fileMenu);
                   setMenuBar(menuBar);
              //------------------------------------------------------------ End setupMenuBar-----------
              //============================================================ Start showpane1 =========
              void showpane1() // REPORTS TAB WITH JTABLE
                   p1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Student Reports 1"));
    p1.setBounds(new Rectangle(28, 70, 513, 429));
    try
                             Class.forName(driver);
                             Connection connection=DriverManager.getConnection(url);
                             Statement statement = connection.createStatement();
                             String query = "SELECT personID, firstName, surname FROM Person where firstName = '" + jTxtTest.getText() + "'";
                             ResultSet rs = statement.executeQuery(query);
    if (rs == null)
    System.out.println("cannot execute query");
                             ResultSetMetaData rmeta = rs.getMetaData();
                             int numColumns=rmeta.getColumnCount();
    for(int i=1;i<=numColumns;++i)
                                  if(i<=numColumns)
                                       defaulttablemodel.addColumn(rmeta.getColumnName(i));
                             while(rs.next())
                                  for(int i=1;i<=numColumns;++i)
                                       if(i<=numColumns)
                                            tempname = rs.getString(i);
                                            tempcnt=i-1;
                                            data[tempcnt] = tempname;
                                  defaulttablemodel.addRow(data);
                   catch(Exception ex)
         p1.add(new JScrollPane(jtable));
              //------------------------------------------------------------ End showpane1 ------------
              //=========================================================== START MenuItemHandler ======
              class MenuItemHandler implements ActionListener
                   public void actionPerformed(ActionEvent ev)
                        String s=ev.getActionCommand();
                        if(s=="Exit")
                        System.exit(0);
    else if (s=="Preview")
    /**Overridden so we can exit when window is closed*/
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void jButton1_actionPerformed(ActionEvent e) {
    jLabel1.setText(jTxtTest.getText());
    jPanel1.add(p1);
    contentPane.repaint();
    }

    Hi,
    Seems u r new to progrmming.Well u used Jbuilder to write.U wrote good debug statments but forgot to write deubg statment or printstacktrace in excpetions.
    ok here is answer for ur problem.
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class Frame1 extends JFrame {
    JPanel contentPane;
    BorderLayout borderLayout1 = new BorderLayout();;
    String driver="org.gjt.mm.mysql.Driver";
    String url="jdbc:mysql://thienpo-app.thienpo.com/jps";
    String user="";
    String pass="";
    String tempname = "";
    int tempcnt;
    boolean firstTime=false;
    JTabbedPane tabbedPane = new JTabbedPane();
    Object[] data = new Object[20];
    DefaultTableModel defaulttablemodel = new DefaultTableModel();
    JTable jtable = new JTable(defaulttablemodel);
    JPanel p1 = new JPanel();
    JTabbedPane jTabbedPane1 = new JTabbedPane();
    JPanel jPanel1 = new JPanel();
    JTextField jTxtTest = new JTextField();
    JButton jButton1 = new JButton();
    JLabel jLabel1 = new JLabel();
    /**Construct the frame*/
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    /**Component initialization*/
    private void jbInit() throws Exception {
    setupMenuBar();
    contentPane = (JPanel) this.getContentPane();
    this.setSize(new Dimension(554, 532));
    this.setTitle("Frame Title");
    jPanel1.setLayout(null);
    jTxtTest.setBounds(new Rectangle(53, 20, 208, 33));
    jButton1.setText("jButton1");
    jButton1.setBounds(new Rectangle(314, 19, 130, 36));
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    jButton1_actionPerformed(e);
    jLabel1.setBounds(new Rectangle(462, 23, 82, 20));
    contentPane.add(jTabbedPane1, BorderLayout.CENTER);
    jTabbedPane1.add(jPanel1, "jPanel1");
    jPanel1.add(jTxtTest, null);
    jPanel1.add(jButton1, null);
    jPanel1.add(jLabel1, null);
    this.setVisible(true);
    //------------------------------------------------------------ End setup -----------------
    //============================================================ Start setupMenuBar ========
    void setupMenuBar()
    MenuBar menuBar = new MenuBar();
    Menu fileMenu = new Menu("File");
    MenuItem fileExit = new MenuItem("Exit");
    fileExit.addActionListener(new MenuItemHandler());
    fileMenu.add(fileExit);
    MenuItem filePrev = new MenuItem("Preview");
    filePrev.addActionListener(new MenuItemHandler());
    fileMenu.add(filePrev);
    menuBar.add(fileMenu);
    setMenuBar(menuBar);
    //------------------------------------------------------------ End setupMenuBar-----------
    //============================================================ Start showpane1 =========
    void showpane1() // REPORTS TAB WITH JTABLE
    p1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),"Student Reports 1"));
    p1.setBounds(new Rectangle(28, 70, 513, 429));
    try
    Class.forName(driver);
    Connection connection=DriverManager.getConnection(url,user,pass);
    Statement statement = connection.createStatement();
    String query = "SELECT personID, firstName, surname FROM Person where firstName = '" + jTxtTest.getText() + "'";
    System.out.println(" query"+query);
    ResultSet rs = statement.executeQuery(query);
    if (rs == null)
    System.out.println("cannot execute query");
    System.out.println(" query"+query);
    ResultSetMetaData rmeta = rs.getMetaData();
    int numColumns=rmeta.getColumnCount();
    if( !firstTime){
    for(int i=1;i<=numColumns;++i)
    if(i<=numColumns )
    defaulttablemodel.addColumn(rmeta.getColumnName(i));
    firstTime=true;
    while(rs.next())
    for(int i=1;i<=numColumns;++i)
    if(i<=numColumns)
    tempname = rs.getString(i);
    tempcnt=i-1;
    data[tempcnt] = tempname;
    defaulttablemodel.addRow(data);
    catch(Exception ex)
    System.out.println("***********************"+ex);
    p1.add(new JScrollPane(jtable));
    public static void main(String[] args){
         new Frame1();
    //------------------------------------------------------------ End showpane1 ------------
    //=========================================================== START MenuItemHandler ======
    class MenuItemHandler implements ActionListener
    public void actionPerformed(ActionEvent ev)
    String s=ev.getActionCommand();
    if(s=="Exit")
    System.exit(0);
    else if (s=="Preview")
    /**Overridden so we can exit when window is closed*/
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void jButton1_actionPerformed(ActionEvent e) {
    jLabel1.setText(jTxtTest.getText());
    showpane1();
    jPanel1.add(p1);
    contentPane.repaint();
    sreeni,
    [email protected]

  • Another problem with JTable

    Hi,
    I have encountered a problem with JTable, i am trying to display some 15 columns and their values , one of the columns value is null, then the JTable is not displaying its value from this column(which is with null value) onwards.
    Can anybody assiss me in this matter.
    Regards
    khiz_eng

    I don't know If I can fix your problem, but
    I know just that it works on my PC.... It's very very
    slow... I don't know how to insert PageSetUp option... I have to study the problem.....
    However I don't think it's a hard problem....
    I want ask to you if you have found some problems when you are in Editing mode in a cell.....
    in the jdk1.2 version I could save while was in editing mode using the editingStopped method.
    It permit to update all data .... also the data in the cell I was editing.
    in the jdk 1.3 if I use this method It doesn't work properly... It maybe destroy the content object in the Cell..... because I'm able to print all the table except the editing cell (it throw an exception...)
    What's changed????
    I don't know...
    Can u help me?

  • Use JSpinner with JTable

    I have retrieve records from database but as the number of records(rows) are more than 1000 , i want to use JSpinner with JTable. How can i do so?

    you can start by being more clear on what your requirements are.

  • No scrollbar with JTable

    Hello!!
    I'm working with JTable, and that table is larger than the JFrame. I want to attach a scrollbar onto it so that entire table can be viewable...I used JScrollPane in NetBeans.. but it is not working....
    is there any way out???
    plz help!!!
    thanks in adv..

    There's a well known deficiency in JTable that prevents horizontal scrollbars from appearing depending on the specific display options indicated for the JTable instance.
    Some searching the bug database should provide information and a workaround.

  • A problem with JTable

    Hi !
    I have a problem with JTable - would like to use this component as a simple list of rows taken from a database : don't want to be able select or set a focus to a column - want only to be able select and set focus to a row ( just like in the menus). How to disable "focusability" for a cell with JTable ? Could You help me ?
    thnx in advance

    The Border is changed by the renderer, depending on whether the cell has focus or not. So you will need to create custom renderers without a Border. Something like:
    class NoBorderRenderer extends DefaultTableCellRenderer
         public Component getTableCellRendererComponent(
              JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
              super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
              setBorder(null);
              return this;
    }

  • Help with JTable - content of cell disappears when selected

    Hello,
    I have a jTable and I have created a custom cell renderer. It does what it's supposed to do (which is set the background color of all cells with null or "" value to red - as an indication to the user that b4 proceeding he/she has to fill in this cells). The problem is that when I select a red cell, it becomes white and the text value it contains disappears. When I double click I can start typing in a new value.
    I would appreciate any hint why this happens? Ideally I would like the cell to keep its color when clicked or double-clicked and its value, and only when i'm done editing its content and it's not null or empty string to become white.
    I'm including majority of my code (some automatically generated code from Netbeans is not included).
    Thank you very much,
    Laura
    public class DataNormalisation extends javax.swing.JFrame {   
        JTextArea txt=new JTextArea();
        public Object[][] DataSummary;
        public Vector<String> colName;
        MainF p;
        String[] ExpNames;
        /** Creates new form DataNormalisation */
        public DataNormalisation(String[] EN, MainF parent) {
            p=parent;
            ExpNames=EN;
            colName= new Vector<String>();
            colName.add("Sample Name");
            colName.add("Replicate Group");
            DataSummary=new Object[ExpNames.length][2];
            for (int i=0;i<ExpNames.length;i++){
                DataSummary[0]=ExpNames[i];
    initComponents();
    this.jTable1.getTableHeader().setReorderingAllowed(false);
    TableColumn column = jTable1.getColumnModel().getColumn(1);
    column.setCellRenderer(new CustomTableCellRenderer());
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new JTable (new DataModel());
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Data Normalisation");
    jTable1.setAutoCreateRowSorter(true);
    jTable1.setCellSelectionEnabled(true);
    jScrollPane1.setViewportView(jTable1);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration
    class DataModel extends AbstractTableModel {       
    class TML implements TableModelListener{
    public void tableChanged (TableModelEvent e){
    txt.setText(""); // Clear it
    for (int i=0;i<DataSummary.length; i++){
    for (int j=0; j<DataSummary[0].length;j++){
    txt.append(DataSummary[i][j] + " ");
    txt.append("\n");
    public DataModel(){
    addTableModelListener(new TML());
    @Override
    public void setValueAt(Object val, int row, int col){
    DataSummary[row][col]=val;
    fireTableDataChanged();
    @Override
    public boolean isCellEditable(int row, int col){
    return (col != 0);
    public int getRowCount(){
    return DataSummary.length;
    public int getColumnCount(){
    return colName.size();
    public Object getValueAt(int row, int column){   
    return DataSummary[row][column];
    public String getColumnName(int col) {           
    return colName.get(col);
    class CustomTableCellRenderer extends DefaultTableCellRenderer {       
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
    boolean hasFocus, int row, int column) {
    Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if (value == null || value.equals("")) {
    cell.setBackground(Color.red);
    } else cell.setBackground(Color.white);
    return cell;

    Ideally I would like the cell to keep its color when clicked or double-clicked Not sure why is changes color when you click on the cell.
    But when you double click the editor is invoked, which is a JTextField and its background is white by default.
    The code you posted doesn't help because its not executable.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    And don't post NetBeans generated code, because we don't use IDE to write GUI code.
    Also, why did you create a custom TableModel. The DefaultTableModel will store your data for you.

Maybe you are looking for

  • Reading any value from table into a string (Especially date etc..)

    How would I read any value from a table into a string? Currently doing the following... data ret_val type string. select single (wa_map-qes_field) from z_qekko into ret_val where angnr = _angnr. When the source field is a date it bombs though. The re

  • Artefacts appearing on Practice slides when publishing to PDF

    HI All, I have created a 91 slide Captivate Six presentation for an online course. My version of Captivate SIx   is  240. My issue is when I publish to a PDF artefacts appear only on the Practice recorded slides. All other slides in the presentation

  • Has anyone actually managed to install a GNOME theme on 5.10 U6 ?

    n/t Edited by: SlowToady on Nov 23, 2008 4:37 PM

  • Increase MCEX03

    Hi guru, how can deactivate  code MCEX03 ? This code increase 1.5 GB /day  the table ARFCSDATA. How can i resolve this problem? My release SAP R3 Enterprise 4.7 ext 1.10 with SP BASIS SAPKB62040. Pleae help me Thank you MC

  • Installing a new cartridge?????

    How do I change the ink cartridges?  They have a plastic orange thing on the bottom of the cartidge.  Do I take that off?  I'm afraid I will destroy the cartridge.  Thank you, Lorna