Visualizzazione dei risultati da 1 a 6 su 6
  1. #1
    Utente di HTML.it
    Registrato dal
    Nov 2006
    Messaggi
    41

    cast

    sto facendo una Swing ed ho un problema con i tipi di oggetto ora vi scrivo la riga di codice che mi da problemi

    Integer a =(Integer)(table.getValueAt(i,j));
    res[i][j]=a.intValue();


    dove
    table è una Jtable
    res è un int[][]
    table.getValueAT(i,j) restituisce un Object secondo le api

    mi da un errore che java.lang.String nn puo' essere castato ad Integer perchè da questo errore se il metodo restituisce un Object??

  2. #2
    Utente di HTML.it
    Registrato dal
    Nov 2006
    Messaggi
    41

    Object ed Integer

    sto facendo una Swing ed ho un problema con i tipi di oggetto ora vi scrivo la riga di codice che mi da problemi

    Integer a =(Integer)(table.getValueAt(i,j));
    res[i][j]=a.intValue();


    dove
    table è una Jtable
    res è un int[][]
    table.getValueAT(i,j) restituisce un Object secondo le api

    mi da un errore che java.lang.String nn puo' essere castato ad Integer perchè da questo errore se il metodo restituisce un Object??

  3. #3
    Utente di HTML.it L'avatar di andbin
    Registrato dal
    Jan 2006
    residenza
    Italy
    Messaggi
    18,284

    Re: Object ed Integer

    Originariamente inviato da d@ny1983
    sto facendo una Swing ed ho un problema con i tipi di oggetto ora vi scrivo la riga di codice che mi da problemi

    Integer a =(Integer)(table.getValueAt(i,j));
    res[i][j]=a.intValue();


    dove
    table è una Jtable
    res è un int[][]
    table.getValueAT(i,j) restituisce un Object secondo le api

    mi da un errore che java.lang.String nn puo' essere castato ad Integer perchè da questo errore se il metodo restituisce un Object??
    Restituisce Object perché tecnicamente deve poter restituire un oggetto qualunque ... che è appunto sicuramente un "Object".
    Poi quasi sicuramente (e se non hai implementato un tuo table model) l'oggetto reale nella cella è un String.

    Ma non puoi passare da String a Integer con un cast, perché è un cast non valido in quanto String e Integer non sono sulla stessa "linea di ereditarietà".

    Se vuoi ottenere un int (primitivo) da un String fai:

    int a = Integer.parseInt (stringa)

    e naturalmente dovresti catturare l'eccezione NumberFormatException.
    Andrea, andbin.devSenior Java developerSCJP 5 (91%) • SCWCD 5 (94%)
    java.util.function Interfaces Cheat SheetJava Versions Cheat Sheet

  4. #4
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,320
    Il Renderer standard delle celle è una JLabel.
    Quando utilizzi getValueAt() è probabile che ti venga ritornato un oggetto di tipo String e non Integer.
    Devi, quindi, utilizzare il metodo parseInt() statico per la classe Integer per poter lavorare con il numero dato.

    Ad ogni modo, per risolvere questi problemi è sufficiente fare un print del valore ottenuto applicando il metodo getClass() sull'oggetto restituito da getValueAt().


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  5. #5
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    Ti posto un po' di codice

    codice:
    import javax.swing.*;
    import java.awt.*;
    
    
    /**
     *
     * @author Andrea
     */
    public class JTableCast extends JFrame {
        
        private JTable table;
        /** Creates a new instance of JTableCast */
        public JTableCast() {
            super("JTable Test");
            this.setSize(300,300);
            String[] headers = {"Colonna 1", "Colonna 2", "Colonna 3"};
            Object[][] data = new Object[3][4];
            for (int i=1; i <= data.length; i++) {
                for (int j=1; j <= data[0].length; j++) {
                    data[i-1][j-1] = new String((10*i+(j-1)*100)+"");
                    //data[i-1][j-1] = new Integer(10*i+(j-1)*100);
                }
            }        
            table = new javax.swing.JTable(data, headers);
            this.getContentPane().add(new JScrollPane(table));
            //int i = ((Integer)table.getValueAt(2,2)).intValue();
            int i = (new Integer((String)table.getValueAt(2,2))).intValue();
            System.out.println(i);
            this.setVisible(true);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        
        public static void main (String[] args) {
            new JTableCast();
        }    
    }
    Se decommenti le righe commentate e commenti quelle attualmente in escuzione, vedrai che la cosa funziona alla stessa maniera. Tu mi sa che hai mischiato i due casi.
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  6. #6
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,320

    Moderazione

    Ma quante discussioni hai aperto per lo stesso problema!?
    Ho unito le due che c'erano qui perchè entrambe avevano delle risposte.
    La prossima volta le chiudo tutte.


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.