13 Replies - 616 Views - Last Post: 26 April 2012 - 08:58 PM Rate Topic: -----

#1 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 07:37 PM

I am getting a NullPointerException error when I try to load a file from File -> Open. I am loading a text file with random lines of code that will represent a phonebook list. After I load the file I try to use the list and get the error. I have tested the list by replacing "file" in the list else if statement with the direct link to a text document with random words and it loads just fine. Any help would be appreciated as I still have 3 other exams to be studying for.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class PhonebookGUI {
	String enterString = "Enter", findString = "Find", listString = "List", deleteString = "Delete";
	private JFrame JFrame = new JFrame("Phonebook");
	JPanel actionPanel = new JPanel();
	JButton btnEnter = new JButton("Enter");
	JTextField nameText = new JTextField(10);
	JTextField numberText = new JTextField(10);
	JTextField noteText = new JTextField(20);
	JTextField findText = new JTextField(10);
	JTextArea listText = new JTextArea(15, 25);
	JScrollPane scrollPane = new JScrollPane(listText);
	JTextField deleteText = new JTextField(10);
	final JFileChooser fc = new JFileChooser();
	File file = null;
	
	// Create components & set hotkeys
	JRadioButton enterButton = new JRadioButton(enterString);
	JRadioButton findButton = new JRadioButton(findString);
	JRadioButton listButton = new JRadioButton(listString);
	JRadioButton deleteButton = new JRadioButton(deleteString);
	JMenuBar mb = new JMenuBar();
	JMenu mnuFile = new JMenu("File");
	JMenuItem mnuItemOpen = new JMenuItem("Open");
	JMenuItem mnuItemSave = new JMenuItem("Save");
	JMenuItem mnuItemQuit = new JMenuItem("Quit");
	JMenu mnuHelp = new JMenu("Help");
	JMenuItem mnuItemAbout = new JMenuItem("About");

	public PhonebookGUI() {
		// Create hotkeys
		enterButton.setMnemonic(KeyEvent.VK_E);
		enterButton.setActionCommand(enterString);
		findButton.setMnemonic(KeyEvent.VK_F);
		findButton.setActionCommand(findString);
		listButton.setMnemonic(KeyEvent.VK_L);
		listButton.setActionCommand(listString);
		deleteButton.setMnemonic(KeyEvent.VK_D);
		deleteButton.setActionCommand(deleteString);
		mnuItemOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,ActionEvent.CTRL_MASK));
		mnuItemSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK));
		mnuItemQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,ActionEvent.CTRL_MASK));
		mnuItemAbout.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,ActionEvent.ALT_MASK));
		
		// Create a button group for the radio buttons
		ButtonGroup group = new ButtonGroup();
		group.add(enterButton);
		group.add(findButton);
		group.add(listButton);
		group.add(deleteButton);

		// Create a JPanel to throw the buttons onto & add the buttons &place the JPanel in the JFrame
		JPanel radioPanel = new JPanel(new GridLayout(0, 1));
		radioPanel.add(enterButton);
		radioPanel.add(findButton);
		radioPanel.add(listButton);
		radioPanel.add(deleteButton);
		JFrame.getContentPane().add(radioPanel, BorderLayout.WEST);

		// Add the menu bar to the JFrame & add the menu components to the menu
		JFrame.setJMenuBar(mb);
		mnuFile.add(mnuItemOpen);
		mnuFile.add(mnuItemSave);
		mnuFile.add(mnuItemQuit);
		mnuHelp.add(mnuItemAbout);
		mb.add(mnuFile);
		mb.add(mnuHelp);

		// Action listeners for the menu bar components, radio buttons and window closing
		JFrame.addWindowListener(new ListenCloseWdw());
		mnuItemOpen.addActionListener(new ListenMenuOpen());
		mnuItemSave.addActionListener(new ListenMenuSave());
		mnuItemQuit.addActionListener(new ListenMenuQuit());
		mnuItemAbout.addActionListener(new ListenMenuAbout());
		enterButton.addActionListener(new ListenAction());
		findButton.addActionListener(new ListenAction());
		listButton.addActionListener(new ListenAction());
		deleteButton.addActionListener(new ListenAction());
	}
	
	public class ListenAction implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			// Action if "Enter" is selected
			if ("Enter".equals(e.getActionCommand())) {
				// Clear actionPanel
				actionPanel.removeAll();
				
				// Place the new JPanel and add components to it
				actionPanel = new JPanel(new GridLayout(7, 7));
				actionPanel.add(new JLabel("Name: "));
				actionPanel.add(nameText);
				actionPanel.add(new JLabel("Number: "));
				actionPanel.add(numberText);
				actionPanel.add(new JLabel("Note: "));
				actionPanel.add(noteText);
				actionPanel.add(btnEnter);
				JFrame.getContentPane().add(actionPanel, BorderLayout.EAST);
				actionPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
				actionPanel.repaint();

				// Update actionPanel
				actionPanel.updateUI();
			}
			// Action if "Find" is selected
			else if ("Find".equals(e.getActionCommand())) {
				// Clear actionPanel
				actionPanel.removeAll();
				
				// Place the new JPanel and add components to it
				actionPanel = new JPanel(new GridLayout(7, 7));
				actionPanel.add(new JLabel("Find: "));
				actionPanel.add(findText);
				actionPanel.add(btnEnter);
				JFrame.getContentPane().add(actionPanel, BorderLayout.CENTER);
				actionPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
				actionPanel.repaint();

				// Update actionPanel
				actionPanel.updateUI();
			}
			// Action if "List" is selected
			else if ("List".equals(e.getActionCommand())) {
				// Read the Phonebook from the .txt file
				try {
				    FileReader fileReader = new FileReader(file);
				    BufferedReader bufferedReader = new BufferedReader(fileReader);
				    String line_from_file;
				    while ((line_from_file = bufferedReader.readLine()) != null)
				        listText.append(line_from_file + "\n");
				    bufferedReader.close();
				}
				catch(Exception e2) { System.out.println(e2); }
				
				// Throws the contact list into a message dialog
				listText.setEditable(false);
				JOptionPane.showMessageDialog(null, scrollPane, "Phonebook List", 1, null);
			}
			// Action if "Delete" is selected
			else if ("Delete".equals(e.getActionCommand())) {
				// Clear actionPanel
				actionPanel.removeAll();
				
				// Place the new JPanel and add components to it
				actionPanel = new JPanel(new GridLayout(7, 7));
				actionPanel.add(new JLabel("Delete: "));
				actionPanel.add(deleteText);
				actionPanel.add(btnEnter);
				JFrame.getContentPane().add(actionPanel, BorderLayout.CENTER);
				actionPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
				actionPanel.repaint();
				
				// Update actionPanel
				actionPanel.updateUI();
			}

		}

	}
	
	// Action listener for Menu -> Quit
	public class ListenMenuQuit implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			System.exit(0);
			// TODO Auto-generated method stub
		}
	}
	
	// Action listener for Menu -> Open
	public class ListenMenuOpen implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			File holder;
			if(e.getSource() == mnuItemOpen) {
				int state = fc.showOpenDialog(JFrame);
				holder = fc.getSelectedFile();
				if(state == JFileChooser.APPROVE_OPTION && file != null) {
					file = holder;
				}
			}
		}
	}
	
	// Action listener for Menu -> Save
	public class ListenMenuSave implements ActionListener {
		public void actionPerformed(ActionEvent e) {

		}
	}
	
	// Action listener for About -> Help
	public class ListenMenuAbout implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			JOptionPane.showMessageDialog(null, "PhonebookGUI v1.0\n\n" +
					" The\"Enter\" command is for entering an new entry in your phonebook\n" +
					" The \"Find\" command is for finding a contact in your phonebook\n" +
					" The \"List\" command is for listing your phonebook\n" +
					" The \"Delete\" command is for deleting an entry in your phonebook\n", "PhonebookGUI Help", 2);
		}
	}
	
	// Action listener for closing the window
	public class ListenCloseWdw extends WindowAdapter {
		public void windowClosing(WindowEvent e) {
			System.exit(0);
		}

	}
	
	// Creating properties of the JFrame and applying them to the frame
	public void launchFrame() {
		JFrame.setPreferredSize(new Dimension(325, 225));
		JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JFrame.pack();
		JFrame.setVisible(true);
	}
	
	public static void main(String[] args) {
		PhonebookGUI gui = new PhonebookGUI();
		
		// Launching the GUI
		gui.launchFrame();
	}
}


Is This A Good Question/Topic? 0
  • +

Replies To: NullPointerException Error, HELP PLEASE

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 07:44 PM

Post your stack trace... it will be a lot clearer. And we can teach you how to read it
Was This Post Helpful? 0
  • +
  • -

#3 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 07:51 PM

View Postpbl, on 26 April 2012 - 07:44 PM, said:

Post your stack trace... it will be a lot clearer. And we can teach you how to read it


I am sorry but I don't think my professor covered that. I will look for a way to get you the stack trace bear with me please.
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 07:55 PM

If you know that there is a "null pointer Exception" it is because the program throwed a stack trace to you.

It is:

null pointer Exception in methodName at JavaFileName at line 1234
called from MethodName JavaFileNAme at line 3456
....
Was This Post Helpful? 0
  • +
  • -

#5 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 07:59 PM

Oh the Console window. I apologize. When I run the code, load the text file and click list all the Console window prints is:

java.lang.NullPointerException

which when clicked brings up a menu to add a Java Exception Breakpoint. If I stop the code the window still just has the NullPoint error.
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 08:05 PM

Cut & paste your code
Try to open a file... nothing happens and no Exception

	// Action listener for Menu -> Open
	public class ListenMenuOpen implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			File holder;
			if(e.getSource() == mnuItemOpen) {
				int state = fc.showOpenDialog(JFrame);
				holder = fc.getSelectedFile();
				if(state == JFileChooser.APPROVE_OPTION && file != null) {
					file = holder;
// and what do you do after ?  File contains the file to read but you do nothing with it
				}
			}
		}
	}


Was This Post Helpful? 0
  • +
  • -

#7 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 08:17 PM

View Postpbl, on 26 April 2012 - 08:05 PM, said:

Cut & paste your code
Try to open a file... nothing happens and no Exception

	// Action listener for Menu -> Open
	public class ListenMenuOpen implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			File holder;
			if(e.getSource() == mnuItemOpen) {
				int state = fc.showOpenDialog(JFrame);
				holder = fc.getSelectedFile();
				if(state == JFileChooser.APPROVE_OPTION && file != null) {
					file = holder;
// and what do you do after ?  File contains the file to read but you do nothing with it
				}
			}
		}
	}



I was attempting to confirm that the desired file was loaded by printing it via the "List" option.

else if ("List".equals(e.getActionCommand())) {
				// Read the Phonebook from the .txt file
				try {
				    FileReader fileReader = new FileReader(file);
				    BufferedReader bufferedReader = new BufferedReader(fileReader);
				    String line_from_file;
				    while ((line_from_file = bufferedReader.readLine()) != null)
				        listText.append(line_from_file + "\n");
				    bufferedReader.close();
				}
				catch(Exception e2) { System.out.println(e2); }
				
				// Throws the contact list into a message dialog
				listText.setEditable(false);
				JOptionPane.showMessageDialog(null, scrollPane, "Phonebook List", 1, null);
			}


Is there an easier way to test if the file is being loaded?
Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 08:26 PM

Because you catch it :)

file is null

				try {
					System.out.println("File to read: " + file);
				    FileReader fileReader = new FileReader(file);
				    BufferedReader bufferedReader = new BufferedReader(fileReader);
				    String line_from_file;
				    while ((line_from_file = bufferedReader.readLine()) != null)
				        listText.append(line_from_file + "\n");
				    bufferedReader.close();
				}
				catch(Exception e2) { 
					System.out.println("In the catch");
					System.out.println(e2); 
					e2.printStackTrace();
				}



File to read: null
In the catch
java.lang.NullPointerException
java.lang.NullPointerException
at java.io.FileInputStream.<init>(FileInputStream.java:103)
at java.io.FileReader.<init>(FileReader.java:55)
at PhonebookGUI$ListenAction.actionPerformed(PhonebookGUI.java:136)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 08:33 PM

Hehe .... when you Open the file

if(state == JFileChooser.APPROVE_OPTION && file != null) {

you sure you want a file != null there ?
Was This Post Helpful? 0
  • +
  • -

#10 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 08:33 PM

View Postpbl, on 26 April 2012 - 08:26 PM, said:

Because you catch it :)

file is null

				try {
					System.out.println("File to read: " + file);
				    FileReader fileReader = new FileReader(file);
				    BufferedReader bufferedReader = new BufferedReader(fileReader);
				    String line_from_file;
				    while ((line_from_file = bufferedReader.readLine()) != null)
				        listText.append(line_from_file + "\n");
				    bufferedReader.close();
				}
				catch(Exception e2) { 
					System.out.println("In the catch");
					System.out.println(e2); 
					e2.printStackTrace();
				}



File to read: null
In the catch
java.lang.NullPointerException
java.lang.NullPointerException
at java.io.FileInputStream.<init>(FileInputStream.java:103)
at java.io.FileReader.<init>(FileReader.java:55)
at PhonebookGUI$ListenAction.actionPerformed(PhonebookGUI.java:136)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)


I think that is because in the public class PhonebookGUI I have "File file = null;" but I removed the = null; and it still does the exception error. Or is the file somehow becoming null elsewhere in the code.

Stupid question, what exactly is a null file? I ask because the fill I am trying to load says:

name
number
note
name
number
note

about 50 times.
Was This Post Helpful? 0
  • +
  • -

#11 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 08:35 PM

Read my post #9
Was This Post Helpful? 1
  • +
  • -

#12 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 08:36 PM

You sir are amazing. Thank you so very much for pointing out that dumb mistake. If you still feel like educating me I would love to know how a file can be null even if it contains characters. If not I understand and yet again thank you very much.
Was This Post Helpful? 0
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 08:54 PM

It is not the File that contains or not characters

It is the File object that has been initialized or not

File file = null;
System.out.println(file); will print null
file = new File("foo.txt");
System.out.println(file); will print foo.txt (not the contain of foo.txt)
Was This Post Helpful? 0
  • +
  • -

#14 BigD959919  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 91
  • Joined: 26-March 12

Re: NullPointerException Error, HELP PLEASE

Posted 26 April 2012 - 08:58 PM

Makes much sense. Thanks again for taking the time to explain my error. Very much appreciated, really thank you.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1