Exception problem...

  • Thread starter steve_marjoribanks
  • Start date
S

steve_marjoribanks

I am having some problems with part of my code. It is a couple of
methods which are part of a much larger class but I'm fairly certain
this is where the problems are. Specifically the 'buffer.close();'
line. It all compiles fine but then throws a NullPointerException
runtime exception saying 'Exception in thread "AWT-EventQueue-0" . I'm
new to Java and have tried a few things but it keeps on doing the same
thing. I think it's probably me not quite fully understanding one of
the methods I've used or something.
Thanks in advance for any help! :)

Steve



public void loadFileChooser()
{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.CANCEL_OPTION) return;
File filename = chooser.getSelectedFile();
if (filename == null || filename.getName().equals("") )
{
JOptionPane.showMessageDialog(this,"Invalid File Name","Invalid File
Name",JOptionPane.ERROR_MESSAGE);
}
else
{
try
{
BufferedReader buffer = new BufferedReader(new
FileReader(filename));

// enable close button and disable load button (currently, only one
buffer may be open at once)
menuLoad.setEnabled(false);
menuClose.setEnabled(true);
toolbarLoad.setEnabled(false);
toolbarClose.setEnabled(true);

// test
boolean eof = false;
while (!eof)
{
String lineInput = buffer.readLine();
String printLine = "\n" + lineInput;
if (lineInput == null)
{
eof = true;
}
else
{
blank.append(printLine);
}
}
}
catch (IOException openError)
{
JOptionPane.showMessageDialog(this, "Error Opening File", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}


public void closeFile()
{
try
{
blank.setText("");
buffer.close();
menuLoad.setEnabled(true);
menuClose.setEnabled(false);
toolbarLoad.setEnabled(true);
toolbarClose.setEnabled(false);
}
catch (IOException closeError)
{
JOptionPane.showMessageDialog(this, "Error Closing File", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
 
L

Lothar Kimmeringer

It all compiles fine but then throws a NullPointerException
runtime exception saying 'Exception in thread "AWT-EventQueue-0" . I'm
new to Java and have tried a few things but it keeps on doing the same
thing. I think it's probably me not quite fully understanding one of
the methods I've used or something.

The complete stacktrace would help a lot. Especially the information
in what line exactly the exception occured.


Regards, Lothar
--
Lothar Kimmeringer E-Mail: (e-mail address removed)
PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)

Always remember: The answer is forty-two, there can only be wrong
questions!
 
S

steve_marjoribanks

Ok, sorry. The command line output given by the exception is this:


Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Application.closeFile(GMLV.java:179)
at Application.actionPerformed(GMLV.java:103)
at javax.swing.AbstractButton.fireActionPerformed(Unknown
Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown
Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown
Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
ce)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown
Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown
Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at
java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)


So the exception is related to the 'Close' button to close a file.
Here is the full code, it might not be the most efficient or elegant
code, but it is my first attempt at a Java application so I'm not too
worried about that as long as it works! ;-)


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

public class GMLV
{
public static void main(String args[])
{
Application application = new Application();
}
}


class Application extends JFrame implements ActionListener
{
// create components to make them globally available to event handlers
// create toolbar buttons
JButton toolbarLoad = new JButton("Load");
JButton toolbarClose = new JButton("Close");
JButton toolbarHelp = new JButton("Help");

// create menu and items
JMenuItem menuLoad = new JMenuItem("Load");
JMenuItem menuClose = new JMenuItem("Close");
JMenuItem menuExit = new JMenuItem("Exit");
JMenuItem menuAbout = new JMenuItem("About");
JMenuItem menuOverview = new JMenuItem("Overview");
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenu helpMenu = new JMenu("Help");
public JTextArea blank = new JTextArea(30, 70);

// create input
public FileReader fileReader;
public BufferedReader buffer;

// constructor
public Application()
{
super("GeotechML Visualizer");
int windowWidth = 800;
int windowHeight = 650;

// set window to centre of screen
Point center =
GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
setBounds(center.x-windowWidth/2, center.y-windowHeight/2,
windowWidth, windowHeight);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

// add toolbar button event listeners
toolbarLoad.addActionListener(this);
toolbarClose.addActionListener(this);
toolbarHelp.addActionListener(this);

// add toolbar buttons to toolbar
JToolBar toolbar = new JToolBar();
toolbar.add(toolbarLoad);
toolbar.add(toolbarClose);
toolbar.add(toolbarHelp);

// add menu item event listeners
menuLoad.addActionListener(this);
menuClose.addActionListener(this);
menuExit.addActionListener(this);
menuOverview.addActionListener(this);
menuAbout.addActionListener(this);

// add items to menu
fileMenu.add(menuLoad);
fileMenu.add(menuClose);
fileMenu.addSeparator();
fileMenu.add(menuExit);
helpMenu.add(menuOverview);
helpMenu.add(menuAbout);
menubar.add(fileMenu);
menubar.add(helpMenu);

// add components to container
menuLoad.setEnabled(true);
menuClose.setEnabled(false);
toolbarLoad.setEnabled(true);
toolbarClose.setEnabled(false);
blank.setEditable(false);
JScrollPane scroll = new JScrollPane(blank);
BorderLayout mainLayout = new BorderLayout();
setLayout(mainLayout);
setJMenuBar(menubar);
add(scroll, "Center");
add(toolbar, "North");
pack();
}

public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();

// toolbar button events
if (source==toolbarLoad) {
this.loadFileChooser();
}
if (source==toolbarClose) {
this.closeFile();
}
if (source==toolbarHelp) {
HelpWindow help = new HelpWindow();
}

// menu item events
if (source==menuClose) {
this.closeFile();
}
if (source==menuLoad) {
this.loadFileChooser();
}
if (source==menuExit) {
System.exit(0);
}
if (source==menuOverview) {
HelpWindow help = new HelpWindow();
}
if (source==menuAbout) {
AboutWindow about = new AboutWindow();
}
}

public void loadFileChooser()
{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.CANCEL_OPTION) return;
File filename = chooser.getSelectedFile();
if (filename == null || filename.getName().equals("") )
{
JOptionPane.showMessageDialog(this,"Invalid File Name","Invalid File
Name",JOptionPane.ERROR_MESSAGE);
}
else
{
try
{
BufferedReader buffer = new BufferedReader(new
FileReader(filename));

// enable close button and disable load button (currently, only one
buffer may be open at once)
menuLoad.setEnabled(false);
menuClose.setEnabled(true);
toolbarLoad.setEnabled(false);
toolbarClose.setEnabled(true);

// test
boolean eof = false;
while (!eof)
{
String lineInput = buffer.readLine();
String printLine = "\n" + lineInput;
if (lineInput == null)
{
eof = true;
}
else
{
blank.append(printLine);
}
}
}
catch (IOException openError)
{
JOptionPane.showMessageDialog(this, "Error Opening File", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}


public void closeFile()
{
try
{
blank.setText("");
buffer.close();
menuLoad.setEnabled(true);
menuClose.setEnabled(false);
toolbarLoad.setEnabled(true);
toolbarClose.setEnabled(false);
}
catch (IOException closeError)
{
JOptionPane.showMessageDialog(this, "Error Closing File", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}


class AboutWindow extends JFrame implements ActionListener
{
JButton closeButton = new JButton("Close");

public AboutWindow()
{
super("About GeotechML Visualizer");
int aboutWindowWidth = 400;
int aboutWindowHeight = 250;
String about = "\n\nA Java visualizer for GeotechML data
files\nDeveloped as part of Stephen Marjoribanks' MEng final year
project\nVersion 0.1b\n\nCopyright 2006, S Marjoribanks, University of
Durham\n\n";

// set window to centre of screen
Point center =
GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
setBounds(center.x-aboutWindowWidth/2, center.y-aboutWindowHeight/2,
aboutWindowWidth, aboutWindowHeight);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);

// create layout
BorderLayout aboutLayout = new BorderLayout();
setLayout(aboutLayout);

// create and add components
setResizable(false);
JPanel aboutPanel = new JPanel();
JTextArea aboutText = new JTextArea(about);
aboutText.setEditable(false);
closeButton.addActionListener(this);
aboutPanel.add(aboutText, BorderLayout.CENTER);
add(closeButton, BorderLayout.SOUTH);
add(aboutPanel);
pack();
}

public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if (source==closeButton) {
dispose();
}
}
}

// HelpWindow class will be modified later to contain help information
class HelpWindow extends JFrame
{
public HelpWindow()
{
super("GeotechML Visualizer Help");
int helpWindowWidth = 400;
int helpWindowHeight = 500;
String help = "Enter help information here\n";

// set window to centre of screen
Point center =
GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
setBounds(center.x-helpWindowWidth/2, center.y-helpWindowHeight/2,
helpWindowWidth, helpWindowHeight);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);

// create container
JPanel helpPanel = new JPanel();
BorderLayout helpLayout = new BorderLayout();
helpPanel.setLayout(helpLayout);
JTextArea textArea = new JTextArea(help);
textArea.setEditable(false);
JScrollPane scroll = new JScrollPane(textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
helpPanel.add(scroll);
add(helpPanel);
pack();
}
}



Thanks for your help!

Steve
 
O

Oliver Wong

I am having some problems with part of my code. It is a couple of
methods which are part of a much larger class but I'm fairly certain
this is where the problems are. Specifically the 'buffer.close();'
line. It all compiles fine but then throws a NullPointerException
runtime exception saying 'Exception in thread "AWT-EventQueue-0" . I'm
new to Java and have tried a few things but it keeps on doing the same
thing. I think it's probably me not quite fully understanding one of
the methods I've used or something.
Thanks in advance for any help! :)

Steve

Could it be that "buffer" is equal to null?

If you don't know what that means, see
http://www.jspwiki.org/wiki/NullPointerExceptions

To fix it, see
http://mindprod.com/jgloss/runerrormessages.html#NULLPOINTEREXCEPTION

- Oliver
 
V

Vova Reznik

Looks like you have class variable
BufferedReader buffer
that never gets initialized. That is why NullPointerException

In loadFileChooser method you probably cover your class variable
BufferedReader buffer = new BufferedReader(.......
You may replace it with
buffer = new BufferedReader(.......

Or, if you have another place to initialize class variable buffer
then check
if(buffer != null){
buffer.close();
}
 
L

Lothar Kimmeringer

at Application.closeFile(GMLV.java:179)

I'm not starting counting the lines below ;-) but if
line 179 is
buffer.close();

in closeFile, then the reason might be that you initialize
buffer in loadFileChooser() with
BufferedReader buffer = new BufferedReader(new FileReader(filename));

You define a local variable with the same name like the
global one. The global one remains null.

Just leave away the BufferedReader in front of buffer and it
should work.


Regards, Lothar
--
Lothar Kimmeringer E-Mail: (e-mail address removed)
PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)

Always remember: The answer is forty-two, there can only be wrong
questions!
 
R

Roedy Green

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Application.closeFile(GMLV.java:179)

this sounds suspiciously like your open failed, or was never
attempted, then you tried to close a null handle. I usually do my
closes like this:

if ( os != null )
{
os.close();
os = null;
}

No matter what you do then, you will never try to close the file twice
or when it was not created.
 
S

steve_marjoribanks

Ah yes! Thanks for your help, silly mistake on my part!! I spent a good
45 minutes staring at my code, forgetting all the time that I had
defined the BufferedReader as global and shouldnt define it again
locally. Doh!

Thanks everybody :)

Steve
 
O

Oliver Wong

Ah yes! Thanks for your help, silly mistake on my part!! I spent a good
45 minutes staring at my code, forgetting all the time that I had
defined the BufferedReader as global and shouldnt define it again
locally. Doh!

Just as terminology correction: the "global" BufferedReader isn't
actually "global"; rather, it is a publicly visible "field" of your object.

- Oliver
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,114
Latest member
GlucoPremiumReview
Top