Search code examples
javastringnullpointerexceptionlwjglslick2d

Why does my string from my JComboBox return as null


Tile Selection

protected void myBox(ActionEvent evt) {
    if (patternList.getSelectedItem() != null) {
        System.out.println(patternList.getSelectedItem().toString());
        getImagePath();
    }

public String getImagePath(){
    jk = patternList.getSelectedItem().toString();
    System.out.println(jk);
    return jk;
}

Boxes

 public void TexDefine() throws SlickException, FileNotFoundException{
    TileSelection t = new TileSelection();
    Tex[171]= new Image(t.newSelection);
    textureCollecter();
}


    public int getN(int px, int oy){
    int n;
    if(p==0&&o==0){
        n = 0;
    }else if(p==0){
        n=oy*42;
    }else{
        n=(oy*42)+px;
    }
    return n;
}
if(in.isKeyPressed(Input.KEY_G)){
        TileSelection t = new TileSelection();
        System.out.println(t.jk);
        /*TexTileRenderer(getN(p, o), returnImagePth());*/
    }

I apologise it for bieng messy, but i'm new to slick and a amatuer at java but can you please enlighten me with you genuisness how the String jk when getting transfered between the classes are becoming null. Why is this?

P.S Im using slick and lwjgl libarys just a heads up. Its messy because i have been fiddling around with it and trying to find a solution.

Thanks!


Solution

  •     TileSelection t = new TileSelection();
        System.out.println(t.jk);
    

    At this point if you haven't selected a value/default value the selectedItem return null.

    Set a default selected item in your TileSelection constructor and also assign jk in the constructor after you assign a default selected item:

    patternList.setSelectedIndex(0);//sets first option in combobox to default value
    jk=(String) patternList.getSelectedItem();
    

    EDIT (This is also about the code before your edited the code for TileSelection out):

    Also note this is not a constructor:

    public void TileSelection(){
    }
    

    constructors do not use void keyword, thus calling TileSelection t = new TileSelection(); will not execute the method you want to create the frame and combobox etc so of course jk will be null either drop the void to make this a valid constructor or do:

    TileSelection t = new TileSelection().TileSelection(); 
    

    though I'd say use a constructor rather which will then make this:

    TileSelection t = new TileSelection();
    

    a valid call to creating a new instance of TileSelection.

    And if you followed the advice before my edit you can then:

    System.out.println(t.jk);
    

    Though it's not good practice to expose instance variables as public, but that's for another time. :)