IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Composants Java Discussion :

Problème avec un JTextField


Sujet :

Composants Java

  1. #21
    Membre habitué Avatar de nicgando
    Profil pro
    Inscrit en
    Mars 2006
    Messages
    128
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Mars 2006
    Messages : 128
    Points : 163
    Points
    163
    Par défaut
    Maintenant ton problème c'est le model de ta JTable,

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
    at java.util.Vector.elementAt(Vector.java:431)
    at Bd.Table.model.StockTableData.getValueAt(StockTableData.java:165)
    at javax.swing.JTable.getValueAt(JTable.java:1771)
    at javax.swing.JTable.prepareRenderer(JTable.java:3724)
    Quand elle veut se redessiner elle demande des infos dans le modèle qui n'existe pas ou plus.

    Quel TableModel utilises-tu pour ta JTable ? un TableModel ? un DefaultTableModel ? autre ?

    Le plus simple serait que tu prennes un DefaultTableModel car avec ces méthodes d' insert/update/remove de ligne/colonnes tu ne te soucis pas de cette gestion. Tout dépend de tes besoins.

    Comment mets-tu à jour ce model ?

  2. #22
    Membre régulier
    Inscrit en
    Mai 2003
    Messages
    350
    Détails du profil
    Informations forums :
    Inscription : Mai 2003
    Messages : 350
    Points : 84
    Points
    84
    Par défaut
    voici le debut de la classe
    public class StockTableData extends javax.swing.table.AbstractTableModel {
    static final public ColumnData m_columns[] = {
    new ColumnData( "PC" , 40, JLabel.LEFT ),
    new ColumnData( "Imp" , 40, JLabel.LEFT ),
    new ColumnData( "Com" , 40, JLabel.LEFT ),
    new ColumnData( "NCC" , 100, JLabel.CENTER ),
    new ColumnData( "Article", 100, JLabel.LEFT ),
    new ColumnData( "Date" , 70, JLabel.RIGHT ),
    new ColumnData( "Montant", 160, JLabel.RIGHT ),
    };
    protected String title ="Stock Quotes at ";
    protected SimpleDateFormat m_frm;
    protected Vector m_vector;
    protected java.util.Date m_date; // conflict with
    protected int m_columnsCount = m_columns.length;
    // Unchanged code from section 18.4
    protected int m_sortCol = 0;
    protected boolean m_sortAsc = true;

    protected int m_result = 0;

    public StockTableData() {
    m_frm = new SimpleDateFormat("MM/dd/yyyy");
    }

    public StockTableData(Vector vector) {
    m_frm = new SimpleDateFormat("MM/dd/yyyy");
    m_vector = vector;
    setDefaultData();
    //fireTableDataChanged();
    }

  3. #23
    Membre habitué Avatar de nicgando
    Profil pro
    Inscrit en
    Mars 2006
    Messages
    128
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Mars 2006
    Messages : 128
    Points : 163
    Points
    163
    Par défaut
    Il faudrait tout la classe pour voir comment tu gères l'insert/update/delete de ligne

    Le plus simple reste quand même d'utilisé le DefaultTableModel qui hérite du AbstractTableModel comme toi.

  4. #24
    Membre régulier
    Inscrit en
    Mai 2003
    Messages
    350
    Détails du profil
    Informations forums :
    Inscription : Mai 2003
    Messages : 350
    Points : 84
    Points
    84
    Par défaut
    public class StockTableData extends javax.swing.table.AbstractTableModel {
    static final public ColumnData m_columns[] = {
    new ColumnData( "PC" , 40, JLabel.LEFT ),
    new ColumnData( "Imp" , 40, JLabel.LEFT ),
    new ColumnData( "Com" , 40, JLabel.LEFT ),
    new ColumnData( "NCC" , 100, JLabel.CENTER ),
    new ColumnData( "Article", 100, JLabel.LEFT ),
    new ColumnData( "Date" , 70, JLabel.RIGHT ),
    new ColumnData( "Montant", 160, JLabel.RIGHT ),
    };
    protected String title ="Stock Quotes at ";
    protected SimpleDateFormat m_frm;
    protected Vector m_vector;
    protected java.util.Date m_date; // conflict with
    protected int m_columnsCount = m_columns.length;
    // Unchanged code from section 18.4
    protected int m_sortCol = 0;
    protected boolean m_sortAsc = true;

    protected int m_result = 0;

    public StockTableData() {
    m_frm = new SimpleDateFormat("MM/dd/yyyy");
    }

    public StockTableData(Vector vector) {
    m_frm = new SimpleDateFormat("MM/dd/yyyy");
    m_vector = vector;
    setDefaultData();
    //fireTableDataChanged();
    }

    public void setDefaultData() {
    try {
    m_date = m_frm.parse("4/6/1999");
    }
    catch (java.text.ParseException ex) {
    m_date = null;
    }
    Collections.sort(m_vector, new StockComparator(m_sortCol, m_sortAsc));
    }
    // section 18.5
    public int retrieveData(final java.util.Date date) {
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(date);
    int month = calendar.get(Calendar.MONTH)+1;
    int day = calendar.get(Calendar.DAY_OF_MONTH);
    int year = calendar.get(Calendar.YEAR);

    final String query = "SELECT data.symbol, symbols.name, "+
    "data.last, data.open, data.change, data.changeproc, "+
    "data.volume FROM DATA INNER JOIN SYMBOLS "+
    "ON DATA.symbol = SYMBOLS.symbol WHERE "+
    "month(data.date1)="+month+" AND day(data.date1)="+day+
    " AND year(data.date1)="+year;

    Thread runner = new Thread() {
    public void run() {
    try {
    // Load the JDBC-ODBC bridge driver
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection conn = DriverManager.getConnection(
    "jdbc:odbc:Market", "admin", "");

    Statement stmt = conn.createStatement();
    ResultSet results = stmt.executeQuery(query);

    boolean hasData = false;
    while (results.next()) {
    if (!hasData) {
    m_vector.removeAllElements();
    hasData = true;
    }
    String pc = results.getString(1);
    String imp = results.getString(2);
    String com = results.getString(3);
    String ncc = results.getString(4);
    String article = results.getString(5);
    java.util.Date date = results.getDate(6);
    long montant = results.getLong(7);
    m_vector.addElement(new StockData(pc, imp, com,ncc, article, date, montant));
    }
    results.close();
    stmt.close();
    conn.close();

    if (!hasData) // We've got nothing
    m_result = 1;
    }
    catch (Exception e) {
    e.printStackTrace();
    System.err.println("Load data error: "+e.toString());
    m_result = -1;
    }
    m_date = date;
    Collections.sort(m_vector,
    new StockComparator(m_sortCol, m_sortAsc));
    m_result = 0;
    }
    };
    runner.start();

    return m_result;
    }

    public void setVector(Vector vecor) {
    m_vector = vecor;
    fireTableDataChanged();
    }

    public int getRowCount() {
    //return m_vector==null ? 0 : m_vector.size();
    return 20;
    }

    public int getColumnCount() {
    //return m_columns.length;
    return m_columnsCount;
    }

    // Unchanged code from section 18.4

    public String getColumnName(int column) {
    String str = m_columns[column].m_title;
    if (column==m_sortCol)
    str += m_sortAsc ? " »" : " «";
    return str;
    }

    public boolean isCellEditable(int nRow, int nCol) {
    return false;
    }

    public void setValueAt(Object value, int rowIndex, int columnIndex) {

    Object[] item;
    if (rowIndex >= m_vector.size()) {
    item = new Object[getColumnCount()];
    m_vector.add(item);
    } else {
    item = (Object[]) m_vector.get(rowIndex);
    }

    item[columnIndex] = value.toString();
    //fireTableCellUpdated(rowIndex >= m_vector.size() ? m_vector.size() - 1 : rowIndex, columnIndex);
    fireTableDataChanged();
    }

    public Object getValueAt(int nRow, int nCol) {
    if (m_vector==null) return null;
    if (nRow < 0 || nRow>=getRowCount())
    return "";
    StockData row = (StockData)m_vector.elementAt(nRow);
    switch (nCol) {
    case 0: return row.m_pc;
    case 1: return row.m_imp;
    case 2: return row.m_com;
    case 3: return row.m_ncc;
    case 4: return row.m_article;
    case 5: return row.m_date;
    case 6: return row.m_montant;
    }
    return "";
    }

    public void setTitle(String title) {
    this.title = title;
    }

    public String getTitle() {
    //if (m_date==null) this.title ="Stock Quotes";
    //this.title ="Stock Quotes at "+m_frm.format(m_date);
    return this.title;
    }

    // Unchanged code from section 18.4
    class ColumnListener extends MouseAdapter
    {
    protected JTable m_table;

    public ColumnListener(JTable table) {
    m_table = table;
    }

    public void mouseClicked(MouseEvent e) {
    TableColumnModel colModel = m_table.getColumnModel();
    int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
    int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex();

    if (modelIndex < 0)
    return;
    if (m_sortCol==modelIndex)
    m_sortAsc = !m_sortAsc;
    else
    m_sortCol = modelIndex;

    for (int i=0; i < m_columnsCount; i++) {
    TableColumn column = colModel.getColumn(i);
    column.setHeaderValue(getColumnName(column.getModelIndex()));
    }
    m_table.getTableHeader().repaint();

    Collections.sort(m_vector, new
    StockComparator(modelIndex, m_sortAsc));
    m_table.tableChanged(
    new TableModelEvent(StockTableData.this));
    m_table.repaint();
    }
    }

    //class TML implements TableModelListener {
    // public void tableChange(TableModelEvent e){
    // for (int i=0;i < m_vector.length;i++) {
    // }
    // }

    //}

    class ColumnMovementListener implements TableColumnModelListener
    {
    public void columnAdded(TableColumnModelEvent e) {
    m_columnsCount++;
    }

    public void columnRemoved(TableColumnModelEvent e) {
    m_columnsCount--;
    }

    public void columnMarginChanged(ChangeEvent e) {}
    public void columnMoved(TableColumnModelEvent e) {}
    public void columnSelectionChanged(ListSelectionEvent e) {}
    }
    }

  5. #25
    Membre habitué Avatar de nicgando
    Profil pro
    Inscrit en
    Mars 2006
    Messages
    128
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Mars 2006
    Messages : 128
    Points : 163
    Points
    163
    Par défaut
    Oulala c'est un peu le champ de guerre là dedans

    Entre autre:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    public int getRowCount() {
    //return m_vector==null ? 0 : m_vector.size();
    return 20;
    }
    la partie commentée est bien mieux

    Sinon il y un peu trop de fonctionnalités rassemblées dans ce TableModel (exécution de requête + gestion de mouse listener ...)
    Il faudrait que tu éclate un peu tout ça ou tout du moins que tu simplifies dans un premier temps tout en utilisant un DefaultTableModel. Je me répète mais cela te permettra dans un premier temps de ne pas te soucier du TableModel

    Car ton problème vient de là. Le modèle ne reflète pas les données qu'il y a dedans
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
    at java.util.Vector.elementAt(Vector.java:431)
    at Bd.Table.model.StockTableData.getValueAt(StockTableData.java:165)
    at javax.swing.JTable.getValueAt(JTable.java:1771)
    at javax.swing.JTable.prepareRenderer(JTable.java:3724)
    Ton modèle dit qu'il y a plus de 2 données dedans or c'est faux car ton vecteur n'a qu'une donnée dedans (ou rien dedans)

  6. #26
    Membre régulier
    Inscrit en
    Mai 2003
    Messages
    350
    Détails du profil
    Informations forums :
    Inscription : Mai 2003
    Messages : 350
    Points : 84
    Points
    84
    Par défaut
    Merci beaucoup c'était vraiment la le problème. Au fait j'ai demandé de retourné 20 lignes parce que au lancement je voulais pas avoir une fenètre sans la JTable affiché. Je pense que je vais modifier le code comme suit
    public int getRowCount() {
    return m_vector==null ? 20 : m_vector.size();
    //return 20;
    }

  7. #27
    Membre habitué Avatar de nicgando
    Profil pro
    Inscrit en
    Mars 2006
    Messages
    128
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Mars 2006
    Messages : 128
    Points : 163
    Points
    163
    Par défaut
    Content de t'avoir aidé et que ça marche après tous ces efforts

    Pense à

Discussions similaires

  1. Problème avec mon JTextField
    Par aljessy dans le forum AWT/Swing
    Réponses: 9
    Dernier message: 24/06/2013, 09h12
  2. Problème avec un JTextField
    Par aljessy dans le forum AWT/Swing
    Réponses: 3
    Dernier message: 31/05/2011, 13h12
  3. Problème avec un JTextField
    Par Wamdeus dans le forum Composants
    Réponses: 14
    Dernier message: 30/12/2007, 23h17
  4. Problème avec un JTextField (Event)
    Par Mike888 dans le forum Composants
    Réponses: 3
    Dernier message: 24/06/2007, 16h11
  5. problème avec JTextField
    Par hammag dans le forum Composants
    Réponses: 3
    Dernier message: 15/05/2006, 14h39

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo