Link to home
Start Free TrialLog in
Avatar of dadadude
dadadude

asked on

Null Object EXCEPTION

i will give you an example of my class  because it is big:
public class test{

private Data data;

public test()[
}

public void createData(){
data = new data();
setData(data)
getData().createTable();
}

public void removeRow(){
// THE EXCEPTION IS HAPPENING IN HERE GETDATA() IS GIVING ME A NULL POINTER WHY?
// AND IT IS ALREADY INITIALIZED!!!
JTabee table = getData().gettable();
}

public void setData(data){
this.data = data;
}

public void getData(){
return this.data;
}
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

To what do you assign 'table' ? - i see nothing
Avatar of dadadude
dadadude

ASKER

i am assigning table to JTable table = getData().getTable();

public class Data{
private JTable table;
//code...
public setTable(table){
this.table = table;
}

public getTable(){
return this.table;
}
}

So i am getting Table in class test and assining table in this class to table from class Data.

the problem is that once
public void createData(){
data = new data();
setData(data)
getData().createTable();
}

GetData() becomes NULL; why? it is initialized in this function and i used setData
>>
data = new data();
setData(data)
getData().createTable();
>>

>>JTabee table = getData().gettable();

Is what you posted earlier - no table get create and assigned that i can see
once i leave this method createData() getData becomes null when i use it in other methods.
JTabee table = getData().gettable();
I want to Get JTable table from Class Data.
and assign Table in class test to table of class Data.
what is the problem why it isn't working?
The Problem is not with Table is with getData() it is becoming Null each time
i will make it more simple:
in class test

i have private Data data;

in method BLABLABLA(){
data = new Data();
setData(data);
getData();
// in here getData() is not null
}

once it is used in another method it becomes null!!!!
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
where is your main() method?  do you call createData() before you call removeRow()?
i am using Listeners
i have a button at first i click on like Open.
it calls method CreateData().
so data shouldn't be null cos it is intilializes in this method createData() correct?

once i click on removeRow() method  and call getData() from the same class test.
i receive this Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

if i do system.out.print(getData()) i have NULL on the screen the object becomes null!
can i see your actionPerformed() method?
>>once it is used in another method it becomes null!!!!

It will become null if you replace the original reference to 'data' with another,  local, one and then try to read it again once you're out of the local context (method)
this is the class:
public class MenuOperation extends JFrame implements ActionListener{
   
    private MenuTabs tabs;
    private File f;
    private Data data;
   
    /** Creates a new instance of MenuOperation */
    public MenuOperation(){
       
    }
   
    public void actionPerformed(ActionEvent e) {
        String actionCommande = e.getActionCommand();

        if(actionCommande.equals("Importer Fichier..." )){
            ouvrir();
        }else if(actionCommande.equals("Supprimer Colonne")){
            selectionnerColonne();
         }
   
    // IN THIS METHOD I DO SETDATA()
    private void ouvrir(){
        JFileChooser jfc = new JFileChooser();
        Container c=InfoInterface.getDonnees().getC();
       
        jfc.setCurrentDirectory(new File("."));
        jfc.addChoosableFileFilter(new FiltreExtension("xls", "Fichier EXCEL"));
        jfc.addChoosableFileFilter(new FiltreExtension("xml", "Fichier XML"));
        jfc.addChoosableFileFilter(new FiltreExtension("tree", "Fichier Regress"));
        int resultat = jfc.showOpenDialog(this);
       
        if(resultat == JFileChooser.CANCEL_OPTION){
           
            return;
           
        }else if(resultat == JFileChooser.APPROVE_OPTION){
           
            f = jfc.getSelectedFile();
            String extension = Extension.getExtension(f);
            cd = new ChargementDonnees(f);
            setData(new Data());
            getData().creerTable(cd);
            cn = new ChargementNature(getData());
            setNature(new Nature());
            getNature().creerTable(cn);
            tabs = new MenuTabs();
            tabs.ajoutTab(getNature(), "nature");
            PanelPrincipale panel = new PanelPrincipale(getData(), tabs);
            c.removeAll();
            c.add(panel);
            c.validate();
           
        }
    }
   
 // in this method getData() becomes null
    private void selectionnerColonne() {
        supprimerColonne(getData().getTable(),
                getData().getTable().getColumnModel().getSelectionModel().getLeadSelectionIndex());
    }
 
    public Data getData() {
        return data;
    }
   
    public void setData(Data data) {
        this.data = data;
       
    }
}
what should i do then if it becomes null outside i need to use it in all the methods
data should be used in all the methods. i can't each time create a new one.
can i use inheritence? is it possible to make it extends Data?
where is your object of class test?  you to call setData() and getData from the same test object.
ignore the last message.
YEs setData and getData are called from the same class test
they're in the same class, but i don't see a common object of that class that is calling both methods
what do you mean? i don't understand you.
setData(new Data());
it is initialized
in method createTable();

and in method supprimerColonne(){
// getData() becomes null
}
createTable(){
 setData(new Data());
            getData().creerTable(cd);
}
no problem in method createTable();

in the other methods it becomes null what should i do?
I mean that you should something like:

test t = new test();

... some code


t.setData(new Data());

... some code

JTable table = t.getData().gettable();
In the stack trace of the exception, you should see a line number. Please point to that line in the code
Imagine this class:

class test{
private Data data;

public void initData(){
setData(new Data());
getData(); // fine in here
}

public void blabla(){
getData() = null;// why?
}

setData(){
bla bla}
getData{return data}
in class test i must create object test?
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at Utilites.MenuOperation.selectionnerColonne(MenuOperation.java:159)
        at Utilites.MenuOperation.actionPerformed(MenuOperation.java:58)
i didn't give you the whole Code it is so big.
setData and getData are in class Test is it possible to create object test in class test?
no, but you're using the methods in another class, right?  so you must have a test object there.
no no both setData and getData are in class test.
so i used getData() to get method getTable() from class Data

Both Methods are in the same class Test.
Look at that example please
class test{
private Data data;

public void initData(){
setData(new Data());
getData(); // fine in here
}

public void blabla(){
getData() = null;// why?
}

setData(){
bla bla}
getData{return data}
In selectionnerColonne, split those references up. You call the same method repeatedly unnecessarily anyway.  Start with

Data data = getData(); //test this
JTable table = data.getTable(); // and this
never mind about what i was saying; i didn't notice that you also had getData() and setData() methods in class MenuOperation.

put a System.out.println() statement after this if statement in your code.

else if(resultat == JFileChooser.APPROVE_OPTION){

make sure that that if is evaluating true
private void selectionnerColonne() {
        Data data = getData(); //test this
        JTable table = data.getTable(); // and this

didn't work i am always getting an exception NullExceptionPointer
else if(resultat == JFileChooser.APPROVE_OPTION){
           
            f = jfc.getSelectedFile();
            String extension = Extension.getExtension(f);
            cd = new ChargementDonnees(f);
            setData(new Data());
            getData().creerTable(cd);
            cn = new ChargementNature(getData());
            setNature(new Nature());
            getNature().creerTable(cn);
            tabs = new MenuTabs();
            tabs.ajoutTab(getNature(), "nature");
            PanelPrincipale panel = new PanelPrincipale(getData(), tabs);
            c.removeAll();
            c.add(panel);
            c.validate();
             System.out.println("test") ;
        }

it worked i have test on the screen
data is in the class and it is initialized what is the problem? mmm weird
try changing your setData() method as follows

public void setData(Data d) {
        data = d;
       
    }
i did but it is the same anyway it wont change.
But is it possible that an object becomes null after it has been created?
>>didn't work i am always getting an exception NullExceptionPointer

It's not intended as a solution - it's to isolate the problem. Which object is null?
also, can i see how you add your ActionListeners?
JTable table = data.getTable(); // and this

in here data is null;
well they are called from another class
where i do like that:
 private MenuOperation menuOperation = new MenuOperation();
 menuItem.addActionListener(menuOperation);
i don't think that it is the problem.
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
looks more likely that your problem is is in your Data class, can u post that.
check that it contains a correct table instance.
You may be creating a new Data instance and not setting its table
ok
public class Data extends JPanel{
   
    private JTable table;
    private TableModel model;
    private static boolean availabe;
    private ChargementDonnees donnees;
   
   
    /**
     * Copy constructeur
     * @param _donnees Donnees est un parametre envoyer par la classe ChargementDonnees
     * qui prend les donnees d'un fichier Excel.
     */

    public Data(){
        super();
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));      
    }
   
    public void creerTable(ChargementDonnees donnees){
        setAvailabe(true);
         this.setDonnees(donnees);
        setTable(new JTable(getDonnees()));
        table.setRowSelectionAllowed(false);
        table.setColumnSelectionAllowed(false);
        TableColumnModel tcm = table.getColumnModel();
        JScrollPane jsp = new JScrollPane(getTable());
        JViewport jvp = new JViewport();
        jvp.setView(new RowNumberHeader(getTable()));
        jsp.setRowHeader(jvp);
        add(jsp,BorderLayout.CENTER);
       
    }
   
    /**
     * retourne un objet JTable
     * @return retourne table
     */
    public JTable getTable() {
        return table;
    }
   
    /**
     * ajouter un objet Table
     * @param aTable pour ajouter une table
     */
   
    public static boolean isAvailabe() {
        return availabe;
    }
   
    public static void setAvailabe(boolean aAvailabe) {
        availabe = aAvailabe;
    }
   
    public ChargementDonnees getDonnees() {
        return donnees;
    }
   
    public void setDonnees(ChargementDonnees donnees) {
        this.donnees = donnees;
    }
   
    public void setTable(JTable table) {
        this.table = table;
    }
}
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes i always pass the same object.
Well because class MenuOperation is supposed to handle the actions. this is why
> getData().getTable().getColumnModel().getSelectionModel().getLeadSelectionIndex());

u could also possible have no selection, try the following so you can see whats happening

System.out.println("data="+getData());
System.out.println("table="getData().getTable());
System.out.println("columns="+getData().getTable().getColumnModel());
System.out.println("selection="+getData().getTable().getColumnModel().getSelectionModel);
getData().getTable().getColumnModel().getSelectionModel().getLeadSelectionIndex());
can you post the whole stack trace?
System.out.println("data="+getData());
System.out.println("table="getData().getTable());
System.out.println("columns="+getData().getTable().getColumnModel());
System.out.println("selection="+getData().getTable().getColumnModel().getSelectionModel);
supprimerColonne(getData().getTable(),
        getData().getTable().getColumnModel().getSelectionModel().getLeadSelectionIndex());
private void selectionnerColonne() {
       
       
        System.out.println("data="+getData());
        System.out.println("table="+getData().getTable());
        System.out.println("columns="+getData().getTable().getColumnModel());
        System.out.println("selection="+getData().getTable().getColumnModel().getSelectionModel());
       
        Data data = this.getData();
        JTable table = data.getTable();
       
        supprimerColonne(table,
                table.getColumnModel().getSelectionModel().getLeadSelectionIndex());
    }

stackTrace:
compile:
data=null
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at Utilites.MenuOperation.selectionnerColonne(MenuOperation.java:161)
        at Utilites.MenuOperation.actionPerformed(MenuOperation.java:58)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
        at javax.swing.AbstractButton.doClick(AbstractButton.java:302)
        at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1000)
        at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1041)
        at java.awt.Component.processMouseEvent(Component.java:5488)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
        at java.awt.Component.processEvent(Component.java:5253)
        at java.awt.Container.processEvent(Container.java:1966)
        at java.awt.Component.dispatchEventImpl(Component.java:3955)
        at java.awt.Container.dispatchEventImpl(Container.java:2024)
        at java.awt.Component.dispatchEvent(Component.java:3803)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
        at java.awt.Container.dispatchEventImpl(Container.java:2010)
        at java.awt.Window.dispatchEventImpl(Window.java:1778)
        at java.awt.Component.dispatchEvent(Component.java:3803)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
        at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
debug:
BUILD SUCCESSFUL (total time: 12 seconds)
it is not passing data
And are you sure  ouvrir() gets called *before* actionPerformed()
sorry meaqnt, before             selectionnerColonne()

ie. that the chooser action runs first
Make sure the reference to a valid instance is not getting lost with your gui when you remove stuff from it
well yes first i call ouvrir then i call selectionnerColonne()
it is possible that the error is in the design?
> data=null

that suggestes your ouvrir() has not got executed beforehand as I mentioned above

to safeguard against that use:

if (getData()!=null) {
   supprimerColonne(getData().getTable(),
        getData().getTable().getColumnModel().getSelectionModel().getLeadSelectionIndex());
}
but i mean when i call ouvrir()  get the table in front of me
do you think that inserrercolonne() is being executed before it?
Add the follwoing to check its getting called:

        System.out.println("Opening dialog");
        int resultat = jfc.showOpenDialog(this);
        System.out.println("ooption="+resultat);
       
        if(resultat == JFileChooser.CANCEL_OPTION){
           
            return;
           
        }else if(resultat == JFileChooser.APPROVE_OPTION){

             System.out.println("APPROVED");
             ...
> do you think that inserrercolonne() is being executed before it?

what you have posted suggests that,

*or* you are creating two instances on MenuOperation.
compile:
Opening dialog
ooption=0
APPROVED
option = 0
if result = 0 is that a problem?
it can't be, because it printed "APPROVED"
i think that i will have to design the application again.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
is there a way to post my application so that you can check it?
post the whole code
can you post your gui class?
yes well i will explain it. i created ItemMenu and MenuOutils to be able to create Menu items
dynamically i think that this is the problem.

// This is the main class
public class Donnees extends JFrame  {
   
    // private JFrame frame = new JFrame();
    private JMenuBar menuBar;
    private Container c;

   
    // Constructeur de la classe Donnees
    public Donnees(){
        super("Regression:Menu Principal");    
        setC(getContentPane());
 
    }
    // Methode pour initialize la fenetre principale
    public void initialization(){
       
        // Appelle WindowListener pour fermer la Fenetre
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                exitForm(evt);
            }
        });
       
        // Creation de la barre Menu
       
        menuBar = new JMenuBar();
        // Menu Principale
        MenuOutils m;
        ItemMenu mi;
       
        //Menu Fichier
       m = new MenuOutils("Fichier",'f');
        menuBar.add(m.initialize());
        mi = new ItemMenu("Importer Fichier...");
        m.ajouter(mi.initializer());
        m.Separateur();
        mi = new ItemMenu("Enregistrer sous...");
        m.ajouter(mi.initializer());
        m.Separateur();
        mi = new ItemMenu("Nouveau...");
        m.ajouter(mi.initializer());
        mi = new ItemMenu("Quitter",'q',KeyStroke.getKeyStroke(
                KeyEvent.VK_Q,ActionEvent.CTRL_MASK
                ));
        m.ajouter(mi.initializer());
       
        // Menu Edition
        m = new MenuOutils("Edition",'e');
        menuBar.add(m.initialize());
        mi = new ItemMenu("Inserrer Colonne");
        m.ajouter(mi.initializer());
        mi = new ItemMenu("Supprimer Colonne");
        m.ajouter(mi.initializer());
        m.Separateur();
        mi= new ItemMenu("Inserrer Ligne");
        m.ajouter(mi.initializer());
        mi = new ItemMenu("Supprimer Ligne");
        m.ajouter(mi.initializer());
        m.Separateur();
        mi = new ItemMenu("Copier",'o',KeyStroke.getKeyStroke(
                KeyEvent.VK_C,ActionEvent.CTRL_MASK
                ));
        m.ajouter(mi.initializer());
        mi = new ItemMenu("Couper",'c',KeyStroke.getKeyStroke(
                KeyEvent.VK_X,ActionEvent.CTRL_MASK
                ));
        m.ajouter(mi.initializer());
        mi = new ItemMenu("Coller",'o',KeyStroke.getKeyStroke(
                KeyEvent.VK_V,ActionEvent.CTRL_MASK
                ));
        m.ajouter(mi.initializer());
       
        // Menu Analyse
        m = new MenuOutils("Analyse",'a');
        menuBar.add(m.initialize());
        mi = new ItemMenu("Stat Description");
        m.ajouter(mi.initializer());
        m.Separateur();
        mi = new ItemMenu("Methode 1");
        m.ajouter(mi.initializer());
        mi = new ItemMenu("Methode 2");
        m.ajouter(mi.initializer());
       
        // Menu Aide
        m = new MenuOutils("?",'?');
        menuBar.add(m.initialize());
        mi = new ItemMenu("Version");
        m.ajouter(mi.initializer());
        m.Separateur();
        mi = new ItemMenu("Aide");
        m.ajouter(mi.initializer());
        setJMenuBar(menuBar);
    }

    // Methode pour quitter l'application
    private void exitForm(WindowEvent e) {
        int reponse = JOptionPane.showConfirmDialog(null,
                "Voulez vous quitter?", "quitter", JOptionPane.YES_NO_OPTION);
        if(reponse== JOptionPane.YES_OPTION) {
            dispose();
            System.exit(0);
        }else{
            return;
        }
    }
   
   
    public Container getC() {
        return c;
    }
   
    public void setC(Container c) {
        this.c = c;
    }
 
}

and this is where i assign an action listener:
public class ItemMenu extends JMenuItem  {
    private String nom;
    private int nemonic;
    private KeyStroke key;
    private JMenuItem menuItem;
   
    private MenuOperation menuOperation = new MenuOperation();
   
   
    /**
     * Creates a new instance of ItemMenu
     */
    public ItemMenu(String _nom,int _nemonic,KeyStroke _key) {
        this.setNom(_nom);
        this.setNemonic(_nemonic);
        this.setKey(_key);
    }
   
    public ItemMenu(String _nom) {
        this.setNom(_nom);
    }
   
    public JMenuItem initializer(){
       
        menuItem = new JMenuItem(getNom());      
        menuItem.setMnemonic(Integer.valueOf(getNemonic()));
        menuItem.setAccelerator(getKey());      
        menuItem.addActionListener(menuOperation);
        return menuItem;
    }
   
   
    public String getNom() {
        return nom;
    }
   
    public void setNom(String nom) {
        this.nom = nom;
    }
   
    public int getNemonic() {
        return nemonic;
    }
   
    public void setNemonic(int nemonic) {
        this.nemonic = nemonic;
    }
   
    public KeyStroke getKey() {
        return key;
    }
   
    public void setKey(KeyStroke key) {
        this.key = key;
    }
   
}

so i created an object in class Donnees like mi and give it an actionListener


i wanted  menu items to be added dynamically. it is a nice way but you are right the problem is there i think.
you are create multiple instance of MenuOperation, that's the problem
please can you explain more where do you mean i am creating them?
please. i am lost
move these statements out into your gui class:

MenuOperation menuoperation = new MenuOperation();

menuitem.addActionListener(menuoperation);
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ok i will try it. it is late now it is 1:30 AM working all day.
it is possible to post tomorrow what i tried ?
so that you can comment please?
yes, of course.
IT WORKED!!!!!!!!!!!!!!!! YOU ARE GREAT PEOPLE THANK YOU SOO MUCH!!!!!!!!!!
thank you all!!
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
mm guess that you all deserve gee mmmmmmmmmmmm
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
don't know how to split the points you all deserve 500