Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 15 of 15

Thread: NullPointerException

  1. #1
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default NullPointerException

    Here is my error:
    	at java.awt.Container.add(Unknown Source)
    	at frmClient.panelSetup(frmClient.java:117)
    	at frmClient.<init>(frmClient.java:65)
    	at frmClient.main(frmClient.java:48)


    Here is my code:
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFormattedTextField;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
     
    public class frmClient implements ActionListener{
     
     
    		public static JFrame[] arrFrame = new JFrame[1];
     
    		// Define JPanels for layout
    		public static JPanel[] panel = new JPanel[16];
     
    		// Define labels
    		public static JLabel lblStatus;
     
    		// Define JTextFields
    		public static JFormattedTextField[] txtBox = new JFormattedTextField[75];
     
    		// Define JComboBox's
    		public static JComboBox comBoxA;
     
    		// Define integers
    		public static int[] arrNumber = new int[58];
     
    		// Define doubles
    		public static double[] arrDouble = new double[17];
     
    		// Define JButtons
    		public static JButton btnSave, btnClear, btnClose, btnCalculate;
     
    		// Define boolean
    		public static boolean ctrlLock;
     
    	// Define custom RGB colors for table(s)
    	static Color colTableA = new Color(194, 250, 203);
    	static Color colTableB = new Color(242, 235, 150);
     
    	// Main method
    	public static void main(String[] args) {
    		new frmClient(); 
    	}
     
    	public frmClient(){		
     
    		// Create the main JFrame that will hold all the panels & Add data Frame
    		arrFrame[0] = new JFrame("Company Name");
    		arrFrame[0].setVisible(true);
    		arrFrame[0].setResizable(false);
    		arrFrame[0].setBounds(450, 300, 800, 570);
     
    		// Create panel to hold all of the panels
    		panel[0] = new JPanel();
    		panel[0].setBackground(Color.WHITE);
    		panel[0].setForeground(Color.GREEN);
     
    		// Extracted methods
    		panelSetup();
     
    	}
     
    	private void panelSetup() {
    		// Create panelLogo for the company logo
    		panel[1] = new JPanel();
    		panel[1].add(new JLabel("                                      Factory Emissions                                      "));
     
    		// Create panel1 to hold label(s) at top
    		panel[2] = new JPanel();
    		panel[2].setBackground(Color.WHITE);
    		panel[2].add(new JLabel("Time              "));
    		panel[2].add(new JLabel("Monday          "));
    		panel[2].add(new JLabel("Tuesday           "));
    		panel[2].add(new JLabel("Wednesday          "));
    		panel[2].add(new JLabel("Thursday           "));
    		panel[2].add(new JLabel("Friday                           "));
    		panel[2].add(new JLabel("Weekly Average"));
     
    		// Create panel2 to hold first line of JTextField(s)
    		panel[3] = new JPanel();
    		panel[3].setBackground(Color.WHITE);
     
    		for(int i = 0; i > 74; i++){
     
    			for(int a = 3; a > 14; a++){
    				if(a == 11){
    					// Create panel11 to hold the line seperator(s)
    					panel[a] = new JPanel();
    					panel[a].setBackground(Color.WHITE);
    					panel[a].add(new JLabel("___________________________________________________" +
    							"_______________________________________________________"));
    				} // End IF
    				else {
     
    				panel[a] = new JPanel();
    				panel[a].setBackground(Color.WHITE);
    				txtBox[i] = new JFormattedTextField();
    				txtBox[i].setHorizontalAlignment(JTextField.RIGHT);
    				txtBox[i].setColumns(8);
    				panel[a].add(txtBox[i]);
    				} // End ELSE
    		}
     
    		}
     
    		// Add all the panels to the main panel
    		arrFrame[0].add(panel[0]);
    		panel[0].add(panel[1]);
    		panel[0].add(panel[2]);
    		panel[0].add(panel[3]);
    		panel[0].add(panel[4]);
    		panel[0].add(panel[5]);
    		panel[0].add(panel[6]);
    		panel[0].add(panel[7]);
    		panel[0].add(panel[8]);
    		panel[0].add(panel[9]);
    		panel[0].add(panel[10]);
    		panel[0].add(panel[11]);
    		panel[0].add(panel[12]);
    		panel[0].add(panel[13]);
    		panel[0].add(panel[14]);
    		panel[0].add(panel[15]);
     
    		// Create a new anwser array
    		String[] arrComboBox = new String [2];
    		arrComboBox[0] = "Disabled";
    		arrComboBox[1] = "Enabled";
     
    		// Create comboboxA and add arrComboBox data into selector
    		comBoxA = new JComboBox(arrComboBox);
    		comBoxA.setBackground(Color.white);
    		comBoxA.setForeground(Color.MAGENTA);
    		comBoxA.addActionListener(this);
     
    		// Set boolean state
    		ctrlLock = false;
     
    		// Create panel14 for the buttons & Button settings
    		/*panel14 = new JPanel();
    		panel14.setBackground(Color.WHITE);
    		panel14.add(btnClear = new JButton("Clear this weeks data"));
    		panel14.add(btnCalculate = new JButton("Calculate"));
    		panel14.add(new JLabel("                      "));
    		panel14.add(new JLabel("Lock Controls: "));
    		panel14.add(comBoxA);
    		panel14.add(new JLabel("                      "));
    		panel14.add(btnSave = new JButton("Save Data"));
    		panel14.add(btnClose = new JButton("Close"));
    		*/
     
    		// Add Time & Button ActionListener(s)
    		//btnClear.addActionListener(this);
    		//btnSave.addActionListener(this);
    		//btnClose.addActionListener(this);
    		//btnCalculate.addActionListener(this);
     
    	}
     
     
     
     
    public void actionPerformed(ActionEvent e) {
     
    	// Execute the code if btnCalculate has focus and lock controls is off
    	if(btnCalculate.hasFocus()){
    		if(ctrlLock == false){
     
    		}
    		else if(ctrlLock == true){
    			JOptionPane.showMessageDialog(arrFrame[0], "Control lock is currently enabled");
    		}
    	}
     
    	// Execute the code if btnClose has focus
    	if(btnClose.hasFocus()) { 
    		if(ctrlLock == false){
    			System.exit(0);
    			}
    		else if (ctrlLock == true){
    			JOptionPane.showMessageDialog(arrFrame[0], "Control lock is currently enabled");
    		}
    		}
     
    	if(comBoxA.getSelectedIndex()== 0){
     
    		// Set boolean state
    		ctrlLock = false;
    	}
    	else if(comBoxA.getSelectedIndex()== 1){
    		ctrlLock = true;
    	}
     
    	// Execute the code if btnSave is clicked
    	if(e.getSource() == btnSave){
    		if(ctrlLock == false){
     
    		}
    		else if(ctrlLock == true){
    			JOptionPane.showMessageDialog(arrFrame[0], "Control lock is currently enabled");
    		}
    	}
     
    	// Execute the code if btnClear is clicked
    	if(e.getSource() == btnClear){
    		if(ctrlLock == false){
     
     
     
    		}
    		else if(ctrlLock == true){
    			JOptionPane.showMessageDialog(arrFrame[0], "Control lock is currently enabled");
    		}
    	}	
    }
     
     
     
     
     
     
     
    	//public void week5PM(){
     
    		//intCalculate = intMonI + intTueI + intWedI + intThuI + intFriI;
    		//dblWkI = intCalculate / 5;
    		//txtWAI.setText(Double.toString(dblWkI));
     
    	//}
     
    	//public void calcAverage(){
     
    		//dblCal = dblWkA + dblWkB + dblWkC + dblWkD + dblWkE + dblWkF + dblWkG
    		//+ dblWkH + dblWkI;
     
    		//dblWA = dblCal;
    		//txtWAJ.setText(Double.toString(dblWA));
     
    		//dblWB = dblCal / 9;
    		//txtWAK.setText(Double.toString(dblWB));
     
    	//}
     
    }

    i know its something simple although ive been having this problem ever since i started using for loops. The program starts when compiling and displays up to the 2nd panel. it seems to stop before the JFormattedTextFields come in. I have been looking and i do have a feeling its to do with my for loop. although if somebody could tell me how to solve this before i tackle the problem myself id still be thankful . Also i do know there are similar threads already listed. I had looked at one i tryed a few solutions but had no luck.

    The error lines:
    Line 117: 	panel[0].add(panel[4]);
    Line 65:    // Extracted methods
    		panelSetup();
    Line 48:		new frmClient();

    Thank you in advance. Also i apologize for the beginner question as i am half a sleep been workin to much this week


  2. #2
    Member
    Join Date
    Jun 2011
    Location
    Rhode Island
    Posts
    69
    My Mood
    Bored
    Thanks
    11
    Thanked 7 Times in 6 Posts

    Default Re: NullPointerException

    wow if i had a nickel for every null pointer issue i would be rich...

    Look at this section of your code and tell me what you see

    for (int i = 0; i > 74; i++) {

  3. #3
    Member
    Join Date
    Jun 2011
    Location
    Rhode Island
    Posts
    69
    My Mood
    Bored
    Thanks
    11
    Thanked 7 Times in 6 Posts

    Default Re: NullPointerException

    not sure what the logic is here maybe you can explain:

    for (int i = 0; i < 74; i++) {
     
                for (int a = 3; a > 14; a++) {
                    System.out.println("a is " + a);
                    if (a == 11) {
                        // Create panel11 to hold the line seperator(s)
                        panel[a] = new JPanel();
                        panel[a].setBackground(Color.WHITE);
                        panel[a].add(new JLabel("___________________________________________________" +
                                "_______________________________________________________"));
                    } // End IF
                    else {
     
                        panel[a] = new JPanel();
                        panel[a].setBackground(Color.WHITE);
                        txtBox[i] = new JFormattedTextField();
                        txtBox[i].setHorizontalAlignment(JTextField.RIGHT);
                        txtBox[i].setColumns(8);
                        panel[a].add(txtBox[i]);
                    } // End ELSE
                }
                System.out.println("int count is " + i);
            }

  4. #4
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: NullPointerException

    ye ive just debuged and found its stopping at that line. altho its trying to shove 74 textfields into the first panel of the next for loop. altho it cannot execute any code as that for loop only contains another for loop inside and nothing to make it keep counting i. i guess the real question would be.. what would be the correct syntax to display 7 textfields into the panel then move to the next panel and display another 7 text boxes etc.. would it be seperate for loops i > 7 i > 14 etc...

  5. #5
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: NullPointerException

    wi have 15 panels. stored them in a panel array. 75 JTextFields which are in the txtBox array. the first for loop is suppose todisplay txtBox in the current panel (a) from the second for loop. as ive mentioned above im trying to display 7 txtfields per panel. and the first 3 panels i have already defined the values to put in there which are simply the labels and the company name.

    picture below of what the program shuld look like. and inside the black rectangle is what is currently displaying


    problem.jpg

    the above picture is the code i did earlier. although it was 1800 lines of code as i had declared each variable seperate. so ive narrowed it down using for loops to 250 lines and im sort of new to the for loop syntax.
    Last edited by macko; June 17th, 2011 at 09:17 AM.

  6. #6
    Member
    Join Date
    Jun 2011
    Location
    Rhode Island
    Posts
    69
    My Mood
    Bored
    Thanks
    11
    Thanked 7 Times in 6 Posts

    Default Re: NullPointerException

    I think you have the right idea just backwards.
    take the pannel for loop and add 7 text fields as a for loop

    so something like this:
    for(int i = 0; i < 15; i++){
    // panel start up code
     
    for(int j = 0 ; j < 7; j++){// notice that its less than 7 because i am only using 7 text fields 0-6
    textField = new TextField();
    jPanel[i].add(textField);
    }
     
    //... more code here
    }

    just an example your using your first for loop to create the panel and the second to fill the panel with text fields.

  7. #7
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: NullPointerException

    ok thanks mate ill tackle the rest myself. im just tired to much coding this week. ive fixed the display error up bu simple changing

    for(int a = 3; a < 15; a++)

    to

    for(int a = 3; a < 16; a++)

    it seems i was missing a panel which is what displayed null. as for the 7 textfields per panel ill tackle it myself otherwise ill never learn

    thanks for the help tho uve been helpful pointing out the obvious

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: NullPointerException

    Why are you hard coding magic numbers in for loops vs using a final int with a selfdefining name to define the value. This makes for hard to maintain code.
    Better would be:
    for (int a = StartIndex; a < NbrLeftHandPanels;

  9. #9
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: NullPointerException

    only thing i dont understand is how to actualy use the for loop to display 7 text boxes per panel, in the above picture each row is a seperate panel. if i were to use

    for(int j = 0 ; j < 7; j++)

    would it not keep posting the textfields 1 - 7 through out the whole loop? there are 75 textfields in total. i need to display each of them once not multiple times. or would it be easier to simply use 7 txtfields ? as it will be reading.writng to a file. when reading from the file would it not over write or display the same value multiple times?

  10. #10
    Member
    Join Date
    Jun 2011
    Location
    Rhode Island
    Posts
    69
    My Mood
    Bored
    Thanks
    11
    Thanked 7 Times in 6 Posts

    Default Re: NullPointerException

    Quote Originally Posted by macko View Post
    would it not keep posting the textfields 1 - 7 through out the whole loop? there are 75 textfields in total. i need to display each of them once not multiple times. or would it be easier to simply use 7 txtfields ? as it will be reading.writng to a file. when reading from the file would it not over write or display the same value multiple times?
    if each row is a jPanel and each jPanel has 7 text fields in them you have 15 jPanels and only 12 of them have 7 text fields (12 *7 = 84) I would assume that your only going to write to the panels that only need 7 text fields in them.

    logic 1:
    write a method that will put 7 text fields in a panel
    public void mainMethod(){
    JPanel[] panel = new JPanel[10];
     
    // .. more code here
    JPanel mainPanel = new JPanel();
    for(int i = 0 ; i < 10; i++){
    //use my method in for loop
    methodFor7TextFields(panel[i])
    //add to my main panel
    mainPanel.add(panel[i];
    }
    private void methodFor7TextFields(JPanel panel){
    for(int i = 0 ; i < 7; i++){
    panel.add(new JTextField()):
    }
    since this is an array and your passing in the reference you wont have to worry about returning the panel.

    logic 2:
    first jpanel to take 10 jpanels
    second 10 jpanels need 7 text fields each

    //create first Jpanel
    JPanel mainPanel = new JPanel("main");
    for(int i = 0 ; i < 10; i++){
     
    //make my 10 panels
    JPanel panel = new JPanel();
    for(int i = 0 ; i < 7; i++){
    JTextField text = new JTextField();
    panel.add(text);//add 7 text fields here
    }//end my nested for loop
    mainPanel.add(panel);//add 10 panels to main panel in order
    }//end my first for loop

    hope that helps. Best way I test stuff I don't understand is build a simple test program, Look at the results. This case you can use nested loops and display to consoled.
    example of what i mean run this code here:
    public class NewMain {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
     
            String[] mainString = new String[25];
            String[] firstNameString ={"Bob","Tim","Robert","Julie","Mark"};
            System.out.println("my array has this many elements: " + firstNameString.length);
            String[] lastStringName = {"Roberts","Smith","Google","Java","Sushi"};
            System.out.println("my last name string has this many elements " +lastStringName.length );
            /*loop to assign my new elements */
            int count = 0;
            for (int i = 0; i < firstNameString.length; i++) {
                //nested loop
                for (int j = 0; j < lastStringName.length; j++) {
                mainString[count] = firstNameString[i].concat(" " + lastStringName[j]);//add a space between names
                count++;//increment my mainString
                System.out.println("count is now " + count);
                }
                System.out.println("string name is " + firstNameString[i]);
            }
            for (int i = 0; i < mainString.length; i++) {
     
                System.out.println(mainString[i]);
            }
     
        }
    }
    Last edited by william; June 17th, 2011 at 11:01 AM. Reason: format code

  11. #11
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: NullPointerException

    ok thanks ill look into it first think in the morning.

  12. #12
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: NullPointerException

    also another simple solution to post 7 text boxes per panel using all of the 75 text boxes would be a code similar to this within the for loop:

    if(x == 6 || x == 13 || x == 20 || x == 27 || x == 34 || x == 41 || x == 48 || x == 55 || x == 62 || x == 69){ a++; }

  13. #13
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: NullPointerException

    Quote Originally Posted by macko View Post
    also another simple solution to post 7 text boxes per panel using all of the 75 text boxes would be a code similar to this within the for loop:

    if(x == 6 || x == 13 || x == 20 || x == 27 || x == 34 || x == 41 || x == 48 || x == 55 || x == 62 || x == 69){ a++; }
    Not sure what you're trying to do, or why, but this is equivalent:
    if (x % 7 == 6) { a++; }

  14. #14
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: NullPointerException

    Quote Originally Posted by dlorde View Post
    Not sure what you're trying to do, or why, but this is equivalent:
    if (x % 7 == 6) { a++; }
    O-o i suppose it is. and its simply making 75 text boxes, once the textbox letter x reaches 45 it will add +1 to the panel. in which it willt hen post the next 7 textboxes onto the next panel etc.. and keep going like that. its so i can recieve data out of a text file and display them in the correct textbox

  15. #15
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: NullPointerException

    Quote Originally Posted by macko View Post
    ... its simply making 75 text boxes, once the textbox letter x reaches 45 it will add +1 to the panel. in which it willt hen post the next 7 textboxes onto the next panel etc.. and keep going like that.
    Sorry, makes no sense at all to me. Closest I can get is: you want 75 text boxes, split between multiple panels with 7 text boxes in each panel - yes?

    What does "once the textbox letter x reaches 45 it will add +1 to the panel" mean? How does a letter x reach 45? how can you add +1 to a panel ??

Similar Threads

  1. [SOLVED] NullPointerException on ActionListeners
    By cherryduck in forum What's Wrong With My Code?
    Replies: 2
    Last Post: December 7th, 2010, 04:17 PM
  2. Problem with NullPointerException?
    By scooty199 in forum What's Wrong With My Code?
    Replies: 15
    Last Post: November 6th, 2010, 05:13 PM
  3. [SOLVED] Nullpointerexception
    By kbwalker87 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: October 14th, 2010, 10:33 PM
  4. [SOLVED] NullPointerException
    By javapenguin in forum What's Wrong With My Code?
    Replies: 13
    Last Post: October 1st, 2010, 12:10 AM
  5. NullPointerException
    By bbr201 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 29th, 2010, 07:06 PM