7 Replies - 1840 Views - Last Post: 19 June 2012 - 09:56 AM Rate Topic: -----

#1 SaltyPeaches  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 22-May 11

Java "Exception in thread "main" java.lang.NullPointerExce

Posted 14 June 2012 - 10:35 AM

I am trying to build a program that will read a text file then output that to a JTextArea. I thought I had everything built correctly, but then when I went to debug, I got this error message. I'm not sure what it means. Please keep in mind, I am not a programmer. I'm just a low-level IT guy who happened to take a programming class once, so I'm trying my best at simple programs until I learn the basics. I am using NetBeans to do this, because I am still not very good at designing output without being able to SEE what I'm designing. Any input, good or bad, is appreciated! I want to get better at this!

Here is the error message:

Exception in thread "main" java.lang.NullPointerException
	at test_announcements.TestForm.<init>(TestForm.java:17)
	at test_announcements.TestForm.main(TestForm.java:99)
Java Result: 1


And here is my full source code:

package test_announcements;

import javax.swing.*;
import java.io.*;

public class TestForm extends javax.swing.JFrame {

    TestForm() throws Exception{
        super("TestForm");
        String dir1 = "C:/Users/solba/";
        String dir2 = "Desktop/";
        String fileName = "Test.txt";
        FileReader f=new FileReader(dir1 + dir2 + "/" + fileName);
        BufferedReader brk=new BufferedReader(f);
        String s;
        while((s=brk.readLine())!=null){
            textArea.append(s);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jInternalFrame1 = new javax.swing.JInternalFrame();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList1);

        jInternalFrame1.setVisible(true);

        javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
        jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
        jInternalFrame1Layout.setHorizontalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jInternalFrame1Layout.setVerticalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane3.setViewportView(jTextArea1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(204, 204, 204));

        jLabel1.setFont(new java.awt.Font("Impact", 2, 24)); // NOI18N
        jLabel1.setText("TEST ANNOUNCEMENTS");
        jLabel1.setToolTipText("");

        textArea.setColumns(20);
        textArea.setRows(5);
        jScrollPane2.setViewportView(textArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(74, 74, 74)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 69, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    
    public static void main(String args[]) throws Exception{
               
        TestForm test=new TestForm();
        test.pack();
        test.setVisible(true);
        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
    }
    // Variables declaration - do not modify
    private javax.swing.JInternalFrame jInternalFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea textArea;
    // End of variables declaration
}


Is This A Good Question/Topic? 0
  • +

Replies To: Java "Exception in thread "main" java.lang.NullPointerExce

#2 Ryano121  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 1362
  • View blog
  • Posts: 3,002
  • Joined: 30-January 11

Re: Java "Exception in thread "main" java.lang.NullPointerExce

Posted 14 June 2012 - 10:41 AM

You are trying to use your textArea before it has been instantiated in initComponents().

As a side note try and stay away form GUI generators in Java. They aren't very good at all. They may seem very handy, but as you can probably see from your snippet, they produce horrible, unmaintainable code that makes your head hurt just looking at it. Better off taking some time to learn Swing from scratch. It's not as hard as you may think.
Was This Post Helpful? 3
  • +
  • -

#3 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7756
  • View blog
  • Posts: 13,116
  • Joined: 19-March 11

Re: Java "Exception in thread "main" java.lang.NullPointerExce

Posted 14 June 2012 - 10:43 AM

The stack trace shows you where the error is. Generally, you start at the first line in code that you control - that'll be where the error was triggered.
In this case, it's your line 17:

textArea.append(s);


The problem must be that textArea is not initialized. You initialize it in initComponents (line 32) but that method is not called before you call the constructor, therefore the object is still null.


EDIT: Ninja'd!

This post has been edited by jon.kiparsky: 14 June 2012 - 10:45 AM

Was This Post Helpful? 1
  • +
  • -

#4 SaltyPeaches  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 22-May 11

Re: Java "Exception in thread "main" java.lang.NullPointerExce

Posted 14 June 2012 - 10:57 AM

View PostRyano121, on 14 June 2012 - 10:41 AM, said:

You are trying to use your textArea before it has been instantiated in initComponents().

As a side note try and stay away form GUI generators in Java. They aren't very good at all. They may seem very handy, but as you can probably see from your snippet, they produce horrible, unmaintainable code that makes your head hurt just looking at it. Better off taking some time to learn Swing from scratch. It's not as hard as you may think.


So, I added the initialization before that line of code, like you guys suggested:

        BufferedReader brk=new BufferedReader(f);
        String s;
        textArea = new javax.swing.JTextArea(); //Added initialization
        while((s=brk.readLine())!=null){
            textArea.append(s);
        }


Now it will build to the point of generating a JFrame, but none of my design from the GUI builder is displayed. Maybe you are right about just learning Swing from scratch. Only problem is, I had a really pretty design laid out already. =(

Anyway, I'll copy my code over to TextPad and start fiddling with the Swing components....see if I can't get a nice GUI built on my own. Thanks, guys! ♥

NOTE: Those were incredibly quick posts! And actually helpful too! I will never go back to StackOverflow again..... =P
Was This Post Helpful? 0
  • +
  • -

#5 Ryano121  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 1362
  • View blog
  • Posts: 3,002
  • Joined: 30-January 11

Re: Java "Exception in thread "main" java.lang.NullPointerExce

Posted 14 June 2012 - 11:03 AM

As a kind of ugly cheat method you could just call a method at the end of initComponents to read your file. Or you could build a public method .readFile() that you call in your main method after the frame has been set up.
Was This Post Helpful? 1
  • +
  • -

#6 SaltyPeaches  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 22-May 11

Re: Java "Exception in thread "main" java.lang.NullPointerExce

Posted 19 June 2012 - 09:45 AM

Okay, so I started from scratch, rebuilt my GUI and my file reader. So, here is the new program. I had it debugging fine, but when I tried changing the textArea.append() to textArea.setText(), I got a bunch of error messages that I don't really understand. I tried just swapping it back to append() but they keep popping up.

Here is my code:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test_announcements;

import java.io.FileReader;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * SaltyPeaches
 * Test Run Number 356
 */
public class TestForm extends javax.swing.JFrame {

    public TestForm() throws Exception{
        super("TestForm");
        FileReader f = new FileReader("C:\\Users\\solba\\Desktop\\Test.txt");
        Scanner brk=new Scanner(f);
        while(brk.hasNextLine()){
            String s = brk.nextLine()+"\n";
            textArea.setText(s);
        }
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Impact", 0, 36)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Test Announcements");

        textArea.setColumns(20);
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        textArea.setRows(5);
        textArea.setWrapStyleWord(true);
        jScrollPane1.setViewportView(textArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane1)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 436, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new TestForm().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(TestForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea textArea;
    // End of variables declaration
}



And here is the errors I get:

Jun 19, 2012 11:38:08 AM test_announcements.TestForm$1 run
SEVERE: null
java.lang.NullPointerException
	at test_announcements.TestForm.<init>(TestForm.java:27)
	at test_announcements.TestForm$1.run(TestForm.java:120)
	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
	at java.awt.EventQueue.access$000(EventQueue.java:101)
	at java.awt.EventQueue$3.run(EventQueue.java:666)
	at java.awt.EventQueue$3.run(EventQueue.java:664)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)


Wow! Cancel that! I'm an idiot! Sorry about that! I shouldn't try to do this on only 3 hours of sleep.....

View PostSaltyPeaches, on 19 June 2012 - 09:42 AM, said:

Okay, so I started from scratch, rebuilt my GUI and my file reader. So, here is the new program. I had it debugging fine, but when I tried changing the textArea.append() to textArea.setText(), I got a bunch of error messages that I don't really understand. I tried just swapping it back to append() but they keep popping up.

Here is my code:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test_announcements;

import java.io.FileReader;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * SaltyPeaches
 * Test Run Number 356
 */
public class TestForm extends javax.swing.JFrame {

    public TestForm() throws Exception{
        super("TestForm");
        FileReader f = new FileReader("C:\\Users\\solba\\Desktop\\Test.txt");
        Scanner brk=new Scanner(f);
        while(brk.hasNextLine()){
            String s = brk.nextLine()+"\n";
            textArea.setText(s);
        }
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Impact", 0, 36)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Test Announcements");

        textArea.setColumns(20);
        textArea.setEditable(false);
        textArea.setLineWrap(true);
        textArea.setRows(5);
        textArea.setWrapStyleWord(true);
        jScrollPane1.setViewportView(textArea);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane1)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 436, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new TestForm().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(TestForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea textArea;
    // End of variables declaration
}



And here is the errors I get:

Jun 19, 2012 11:38:08 AM test_announcements.TestForm$1 run
SEVERE: null
java.lang.NullPointerException
	at test_announcements.TestForm.<init>(TestForm.java:27)
	at test_announcements.TestForm$1.run(TestForm.java:120)
	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
	at java.awt.EventQueue.access$000(EventQueue.java:101)
	at java.awt.EventQueue$3.run(EventQueue.java:666)
	at java.awt.EventQueue$3.run(EventQueue.java:664)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

Was This Post Helpful? 0
  • +
  • -

#7 Ryano121  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 1362
  • View blog
  • Posts: 3,002
  • Joined: 30-January 11

Re: Java "Exception in thread "main" java.lang.NullPointerExce

Posted 19 June 2012 - 09:45 AM

You are running into the same problem again. Your constructor is trying to set the text of the textArea which hasn't been instantiated yet because the initComponenets() hasn't yet run.
Was This Post Helpful? 0
  • +
  • -

#8 SaltyPeaches  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 22-May 11

Re: Java "Exception in thread "main" java.lang.NullPointerExce

Posted 19 June 2012 - 09:56 AM

View PostRyano121, on 19 June 2012 - 09:45 AM, said:

You are running into the same problem again. Your constructor is trying to set the text of the textArea which hasn't been instantiated yet because the initComponenets() hasn't yet run.


Yeah, sorry again about that. I got it corrected and now it compiles no problem. But do you know why it isn't writing any of the text to the JTextArea? It finds the file no problem, but it just won't write it. I'm wondering if there is a line of code I'm missing that is clearing textArea after I've already set the text? Or is NetBeans just stupid and I'm missing a checkbox in the JTextArea properties or something? (which I found out was my issue with not being able to setEditable(false) and what-not)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1