Page 1 of 1

Java: basic gui issue

Posted: Sat May 17, 2008 7:42 pm
by afbase
In my IDE, eclipse, I get this error from running my code. Only problem is, I don't exactly why this is occurring. I'm still new to coding in Java, and I'm still learning its finicky ways. Could somebody point me in the right direction in my code?
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at sudoku.buildSudoku_pane(sudoku.java:25)
at sudoku.<init>(sudoku.java:31)
at sudoku.main(sudoku.java:46)

Code: Select all

 
import javax.swing.*;
 
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import java.io.*;
import java.util.*;
import java.lang.Character;
 
 
public class sudoku extends JFrame implements ActionListener{
private JFrame sudoku_frame = new JFrame("Sudoku");
private JButton solve;
private JButton check_if_correct;
private JTextField[] sudoku_entry;
public final static boolean RIGHT_TO_LEFT = false;
public void actionPerformed(ActionEvent e) {}
private void buildSudoku_pane(int number, Container pane, JTextField[] sudoku_entry_array){
    sudoku_entry_array = new JTextField[number*number];
    if (RIGHT_TO_LEFT){
    pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }
    pane.setLayout(new GridLayout(number,number));
    for(int i = 0; i <= (number*number)-1; i++){
        pane.add(sudoku_entry_array[i]);
    }
}
 
public sudoku() {
    int int_default = 9;
    buildSudoku_pane(int_default, sudoku_frame.getContentPane(), sudoku_entry);
    sudoku_frame.pack();
    sudoku_frame.setVisible(true);
}   
 
public sudoku(int number){
    buildSudoku_pane(number, sudoku_frame.getContentPane(), sudoku_entry);
    sudoku_frame.pack();
    sudoku_frame.setVisible(true);
}
 
 
 
public static void main(String[] args) {
 
    sudoku tpo = new sudoku();               // create 'the program object'
 
    tpo.addWindowListener(new WindowAdapter() {   // this exits the program when X box clicked
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
 
} // end of main
 
}
 
 
 

Re: Java: basic gui issue

Posted: Mon May 19, 2008 2:54 pm
by emmbec
In your function buildSudoku_pane() the array sudoku_entry_array is not initialized, it has a length of 81 but filled with NULL objects, so when you are looping, you are accessing its contents and adding them to your pane, and since they are NULL it crashes, that is why it is saying NULL POINTER EXCEPTION 8) look:

Code: Select all

for (int i = 0; i <= (number * number) - 1; i++) {
            pane.add([b]sudoku_entry_array[i][/b]);  [color=#00BF00] //The array contents are NULL therefore Java throws a NULL POINTER EXCEPTION[/color]
        }
Debug your code and you will see.