При запуске программы вылетает вот такой отчёт об ошибке
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at core.Main.sendData(Main.java:76)
at core.Main$1.actionPerformed(Main.java:46)
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 Source)
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.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(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)
Вот часть кода, где вылетает ошибка:
public static void sendData(Object obj) {
try {
output.flush(); //76 строка
output.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
}
}
Вот часть кода, где находится метод, в котором вылетает ошибка
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource() == b1) {
sendData(t1.getText()); //46 строка
}
}
I’m working on a simple calculator program using java and javax.swing
Basically, when you press a button, the program is supposed to fetch the function of that button (number or operation) and display it in the textArea.
The whole logic for the calculator itself doesn’t matter. Also, there’s a clear menu item that clears all the text in textArea.
However, every time a press a button, I get the following error:
Exception in thread «AWT-EventQueue-0» java.lang.NullPointerException
at calculator.CalculatorGUI.actionPerformed(CalculatorGUI.java:106)`
I’m also getting a similar error when I press the clear menu item, it seems like java doesn’t like it when I want to change the text in the text area.
Here’s my code: (Line 106 is in the actionPerfomed method, I’ve labeld it for your convenience)
public class CalculatorGUI implements ActionListener
{
// The calculator for actually calculating!
// private RPNCalculator calculator;
// The main frame for the GUI
private JFrame frame;
// The menubar for the GUI
private JMenuBar menuBar;
// The textbox
private JTextArea textArea;
private JScrollPane scrollArea;
// Areas for numbers and operators
private JPanel numKeysPane;
private JPanel opKeysPane;
private String input;
final String[] numbers = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" };
final String[] operations = { "+", "-", "*", "/" };
/**
* Constructor
*/
public CalculatorGUI() {
// Initialize the calculator
calculator = new RPNCalculator();
}
/**
* Initialize and display the calculator
*/
public void showCalculator() {
String buttonValue;
JButton button;
JMenu menu;
JMenuItem menuItem;
// Create the main GUI components
frame = new JFrame("RPN Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
numKeysPane = new JPanel(new GridLayout(4, 3));
opKeysPane = new JPanel(new GridLayout(2, 2));
initializeMenu();
initializeNumberPad();
initializeOps();
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollArea = new JScrollPane(textArea);
// Create the components to go into the frame and
// stick them in a container named contents
frame.getContentPane().add(numKeysPane, BorderLayout.CENTER);
frame.getContentPane().add(scrollArea, BorderLayout.NORTH);
frame.getContentPane().add(opKeysPane, BorderLayout.LINE_END);
// Finish setting up the frame, and show it.
frame.pack();
frame.setVisible(true);
}
/*
* (non-Javadoc)
*
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
String s = (String)e.getActionCommand();
// calculator.performCommand(s);
textArea.append(s + " "); // <<--- THIS IS LINE 106
}
/**
* Initialize the number pad for the calculator
*/
private void initializeNumberPad() {
JButton button;
for (int i = 0; i < numbers.length; i++) {
button = new JButton(numbers[i]);
button.addActionListener(this);
numKeysPane.add(button);
}
}
private void initializeOps(){
JButton button;
for (int i = 0; i < operations.length; i++){
button = new JButton(operations[i]);
button.addActionListener(this);
opKeysPane.add(button);
}
}
/**
* Initialize the menu for the GUI
*/
private void initializeMenu() {
JMenu menu;
JMenuItem menuItem;
JMenuItem menuItem2;
// Create a menu with one item, Quit
menu = new JMenu("Calculator");
menuItem = new JMenuItem("Quit");
// When quit is selected, destroy the application
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// A trace message so you can see this
// is invoked.
System.err.println("Close window");
frame.setVisible(false);
frame.dispose();
}
});
menuItem2 = new JMenuItem("Clear");
menuItem2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
textArea.setText("");
}
});
menu.add(menuItem2);
menu.add(menuItem);
// Create the menu bar
menuBar = new JMenuBar();
menuBar.add(menu);
frame.setJMenuBar(menuBar);
}
/**
* Helper method for displaying an error as a pop-up
* @param message The message to display
*/
private static void errorPopup(String message) {
JOptionPane.showMessageDialog(null, message);
}
}
Any help would be greatly appreciated! Thanks!

Read on to learn the cause of this error and how you can solve the error.
Contents
- What Causes Exception in Thread “Awt-eventqueue-0” Java.lang.nullpointerexception
- – Example 1: Failure To Call a Constructor on an Object
- – Example 2: Writing Complex Code
- How To Solve It
- – Example 1: Instantiating an Object
- – Example 2: Solving the Complex Code Issue
- – How To Add Null Checks
- FAQs
- – What is Exception in Thread “Awt-eventqueue-0” Java.lang.nullpointerexception?
- – How Can You Solve the Error?
- – How Can You Fix Java Lang NullPointerException
- – What Is AWT Package in Java
- – What Is the Role of EventQueue?
- – What Is the Meaning of Java Lang Nullpointerexception?
- – What Is Java Lang?
- – Why Use Java Lang?
- – In Java, What Is a Runtime Exception?
- – How Do You Overcome Runtime Exception?
- – How Can You Check if a String Is Null?
- Conclusion
One main cause of this error is when you fail to call a constructor on an object but then go ahead and try to use it. Another cause is an accidental declaration of an object in a local scope that has another instance variable using the same name. So, these are the two causes of this Java error. Another cause is writing complex code that makes it difficult to pinpoint the issue.
– Example 1: Failure To Call a Constructor on an Object
Suppose that you are creating a simple check box where a user gets to choose among various choices and depending on what they choose, the image changes to match their choice. If in your code the exception occurs in the constructor for, say Retail on line 25, you will need to evaluate that line.
For instance, if you check the line and you find something like:
brownshirtButton.addItemListener(this);
In this example, it is clear there are two objects in this line that is brownshirtButton and this. Usually, this in Java is popular with the class instance that you are currently in. In this case, you are in the constructor which cannot be this. In such a scenario the brownshirtButton is the culprit. Chances are you did not instantiate that object.
– Example 2: Writing Complex Code
Say you are creating a TicTacToe object. At some point you may end with a code that is as follows:
panels [badg.num].add (newCells [j] [k] = new Cell (this));
If the error message appears on this line, it could indicate a null reference to any of the following:
- panels
- badg
- panels[badg.num
- newCells
- any of New Cells [j]
How To Solve It
To solve this runtime exception issue, you need to first stack trace the source of the problem by reading your code from the top to the bottom. Usually, you will come across exceptions whose origins are in the Java library code. As well, some are in native implementation methods.
To diagnose the problem, skip to the code file you created that is causing the error. You will see a line indicated. The next thing you need to do is to look at all the instantiated classes (objects) individually as long as they fall in that line. Start by establishing if you made a constructor call on that object.
Once it emerges that you never made that call, then that could be the problem that is causing this error. Now, with that understanding, you need to instantiate that object. You can accomplish this by calling a new class name argument.
– Example 1: Instantiating an Object
Suppose you want to solve the issue in the previous example. In this case, you need to solve the brownshirtButton object issue that is generating this error. There are two ways you can avoid the error when creating a simple check box where a user gets to choose between various items, and depending on what they choose, the image changes to match their choice.
In this case, you can opt to get rid of the reference to brownshirtButton instance variable or instantiate it.
– Example 2: Solving the Complex Code Issue
If you are creating a TicTacToe, and you end with a complex code like this:
panels [badg.num].add (newCells [j] [k] = new Cell (this));
You need to step through the error in this line using a debugger to establish the null object. The only way you can establish if the null pointer exception arises from either newCells or panels is by breaking the code into two. Simplifying and eliminating unknowns is essential in debugging.
The code above has a lot of choices that do not work because it is too complicated. Keep in mind that this error is not impossible, the issue is somewhere in the code. To get started, you can include null checks and simplify the code by breaking it into various lines.
– How To Add Null Checks
Like in most things, there are various ways of accomplishing this. There are two options, you can either implement the null check manually or use java.util.Objects.requireNonNull to evaluate each value j lists in the example above. It is appropriate to implement the null check yourself to see how it functions.
You can opt for a bunch of checks as follows:
if (doo == null)
{
throw new NullPointerException(“doo is null”);
}
else if (dee == null)
{
// set the error message you need to show
}
Alternaively, you can choose to perform null checks like so:
Objects.requireNonNull(doo, “doo is null”);
Objects.requireNonNull(dee, “dee is null”);
Whichever method you choose, when you run the code, you will get a crash message that details what is actually taking place.
FAQs
– What is Exception in Thread “Awt-eventqueue-0” Java.lang.nullpointerexception?
This is an exception error in Java that arises when you fail to call a constructor on an object. In other words, Java throws this error when you use a reference variable that does not point to any object. Another cause of the NullPointerException error in Java entails accidentally declaring an object in a local setting where there is another variable using the same name.
– How Can You Solve the Error?
The solution to this error requires you to either get rid of the reference to the instance or instantiate the variable in question. To help you accomplish this, perform null checks on the line causing the error. Also, you can break up complex code to make it easy to pinpoint the cause of the error.
– How Can You Fix Java Lang NullPointerException
You can resolve this error by using an if-else condition or try-catch block to establish if the reference variable in question is null before you can dereference it.
– What Is AWT Package in Java
The AWT (Abstract Window Toolkit) package in Java is an API that let you build GUI or window-based apps. Components of the AWT package are platform-dependent. What this means is that the appearance of components will be under the control of the operating system.
Often, the AWT package is heavyweight because its components use the operating system resources. The package offers various components such as checkboxes, labels, and buttons that are used as objects in Java.
– What Is the Role of EventQueue?
The EventQueue in Java is a public class that extends objects. It is a platform-independent class for queuing events from underlying peer classes as well as reputable application classes.
– What Is the Meaning of Java Lang Nullpointerexception?
In Java, it is a runtime exception that takes place once a variable that does not point to any object is accessed. It means the variable refers to nothing. Due to it is a runtime exception, no need to catch and handle it explicitly in the application code.
– What Is Java Lang?
It provides fundamental classes for the Java programming language. The Object is one of the most important classes since it is at the root of class hierarchy and class which are instances that represent classes in run time.
– Why Use Java Lang?
It provides necessary classes for creating an applet as well as the classes an applet relies on to interact with its applet context. Lang in Java offers classes and interfaces for transmitting data between and inside applications.
– In Java, What Is a Runtime Exception?
In Java programming language, the runtime exception acts as the parent class for all exceptions that crash an application when they occur. They are different from other exceptions since these are never checked.
– How Do You Overcome Runtime Exception?
The easiest way you can handle runtime errors in Java is through the use of try-catch blocks. To do this, you need to surround statements capable of throwing runtime exceptions in try-catch blocks. These catch the error and perform the necessary action depending on the needs of the application. For instance, they can throw the right messages.
– How Can You Check if a String Is Null?
Normally, you can check for null through the strict equality operator (!== or ===) to ensure that the value is not null. For instance, the object1 !== null code checks if the variable object1 is not null.
Conclusion
A runtime exception like the error in question is hard to catch before the program executes. However, there is a way you can solve it. Here is a quick recap:
- The error originates from a reference variable that does not point to any object
- It is a runtime exception that causes an application to crash
- The solution is either you instantiate the object or remove the null reference

- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
- HowTo
- Java Howtos
- Exception in Thread AWT-EventQueue-0 …
Sheeraz Gul
Jul 14, 2022
The "AWT-EventQueue-0" java.lang.NullPointerException exception occurs when we work with Java AWT package methods, and a null value is passed to any method. This tutorial demonstrates how to solve this NullPointerException in Java.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException in Java
The "AWT-EventQueue-0" java.lang.NullPointerException occurs when we pass a null value to the AWT package. The NullPointerException exception is the most common in Java.
The NullPointerException occurs when any of the following conditions meet.
- When accessing and modifying the
nullobject field. - When we invoke a method from a
nullobject. - When accessing and modifying the slots of the
nullobject. - When taking the length of any
nullarray. - When we try to synchronize over a
nullobject. - When we are throwing a
nullvalue.
Let’s try an example that will throw the "AWT-EventQueue-0" java.lang.NullPointerException in Java.
package delftstack;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Timer;
@SuppressWarnings("serial")
public class Example extends JFrame implements ActionListener , KeyListener {
static Dimension Screen_Size = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
Insets Scan_Max = Toolkit.getDefaultToolkit().getScreenInsets(getGraphicsConfiguration());
int Task_Bar_Size = Scan_Max.bottom;
static JFrame Start_Screen = new JFrame("Start Screen");
static JFrame Game_Frame = new JFrame("Begin the Game!");
static JLabel Cow_Label = new JLabel();
static int Sky_Int = 1;
static JLabel Sky_Label = new JLabel();
static int SECONDS = 1;
static boolean IS_Pressed = false;
public static void main(String[] args) {
new Example();
}
public Example() {
JPanel Buttons_Panel = new JPanel();
Buttons_Panel.setLayout(null);
Start_Screen.setSize(new Dimension(Screen_Size.width - getWidth(), Screen_Size.height - Task_Bar_Size - getHeight()));
Start_Screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Start_Screen.setVisible(true);
System.out.println(Start_Screen.getSize());
//buttons
JButton Start_Button = new JButton("Start");
Start_Button.addActionListener(this);
Start_Button.setSize((int) Start_Screen.getWidth()/7, (int) (Start_Screen.getHeight()/15.36));
Start_Button.setBounds((Start_Screen.getWidth()/2) - Start_Button.getWidth()/2,((int)Start_Screen.getHeight()/2) - Start_Button.getHeight(),Start_Button.getWidth(),Start_Button.getHeight());
Start_Button.setActionCommand("Start");
Buttons_Panel.add(Start_Button);
Start_Screen.add(Buttons_Panel);
}
@Override
public void actionPerformed(ActionEvent Action_Event) {
Object CMD_Object = Action_Event.getActionCommand();
if(CMD_Object == "Start") {
Start_Screen.setVisible(false);
// getClass().getResource("/cow.png") and getClass().getResource("/grass.png") is giving null
// because there is no image in folder named cow.png or grass.png
ImageIcon Cow_Image = new ImageIcon(getClass().getResource("/cow.png"));
ImageIcon Grass_Image = new ImageIcon(getClass().getResource("/grass.png"));
Game_Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Game_Frame.setSize(Start_Screen.getSize());
Game_Frame.setVisible(true);
JPanel Demo_Panel = new JPanel();
Demo_Panel.setBackground(Color.white);
Demo_Panel.setLayout(null);
Demo_Panel.setFocusable(true);
Game_Frame.add(Demo_Panel);
Demo_Panel.addKeyListener(this);
Cow_Label.setBounds( (Start_Screen.getWidth()/2)-105, (Start_Screen.getHeight()/2)-55, 210, 111);
Cow_Label.setIcon(Cow_Image);
Demo_Panel.add(Cow_Label);
Demo_Panel.setVisible(true);
Cow_Label.setVisible(true);
JLabel Grass_Label = new JLabel();
System.out.println("grass");
// getClass().getResource("/Sky.png") will throw a nullpointerexception because there is no image in the folder
ImageIcon Sky1 = new ImageIcon(getClass().getResource("/Sky.png"));
Sky_Label.setIcon(Sky1);
Grass_Label.setIcon(Grass_Image);
Grass_Label.setBounds(0, ( Start_Screen.getHeight()-308), Start_Screen.getWidth(), 350);
System.out.println("mOooow");
Demo_Panel.add(Grass_Label);
Sky_Label.setBounds(1, 56, 1366, 364);
Demo_Panel.add(Sky_Label);
System.out.println("google");
}
}
@Override
public void keyPressed(KeyEvent Key_Event) {
int CMD_Int = Key_Event.getKeyCode();
// getClass().getResource("/cow moving.gif") will throw a nullpointerexception because there is no image in the folder
ImageIcon Moving_Cow = new ImageIcon(getClass().getResource("/cow moving.gif"));
System.out.println(CMD_Int);
IS_Pressed = true;
if(CMD_Int == 39){
System.out.println("Key is Pressed");
Cow_Label.setIcon(Moving_Cow);
}
else if(CMD_Int == 37){
}
System.out.println("End");
while(IS_Pressed==true){
Timer Wait_Please = new Timer("Wait Please");
try {
Wait_Please.wait(1000);
}
catch(InterruptedException p){}
int SKY = 1;
SKY += 1;
String SKY_String = "/Sky" + String.valueOf(SKY) + ".png";
ImageIcon SKy = new ImageIcon(getClass().getResource(SKY_String));
Sky_Label.setIcon(SKy);
if(IS_Pressed==false){
Wait_Please.cancel();
break;
}
}
}
@Override
public void keyReleased(KeyEvent Key_Event) {
// getClass().getResource("/cow.png") and getClass().getResource("/grass.png") is giving null
// because there is no image in folder named cow.png or grass.png
ImageIcon Cow_Image = new ImageIcon(getClass().getResource("/cow.png"));
int CMD_Int = Key_Event.getKeyCode();
IS_Pressed = false;
if(CMD_Int == 39){
Cow_Label.setIcon(Cow_Image);
}
else if(CMD_Int == 37){
Cow_Label.setIcon(Cow_Image);
}
}
@Override
public void keyTyped(KeyEvent c) {
// TODO Auto-generated method stub
}
}
The code above is about a simple game with a cow standing, and the cow will start moving on pressing the button. It will throw the "AWT-EventQueue-0" java.lang.NullPointerException because the AWT method new ImageIcon(getClass().getResource()) is getting a null entry.
The output for this code is:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null
at java.desktop/javax.swing.ImageIcon.<init>(ImageIcon.java:234)
at delftstack.Example.actionPerformed(Example.java:48)
at java.desktop/javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1972)
at java.desktop/javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2313)
...
We can solve this issue by moving the images to the class folder path. We can also remove the / as Windows use \ for path in Java.
And if it is still not working, we can give the full path to the images. Further explanations are commented-out in the code above.
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn
Facebook
Related Article — Java Exception
- Understanding Runtime Exception in Java
- Java Throwable VS Exception Class
- Re-Throw Exception in Java
- Throw New Exception in Java
- Throw Runtime Exception in Java
- Java.Lang.ClassNotFoundException: Org.SpringFramework.Web.Servlet.DispatcherServlet
hELLO GUYZ PLEASE HELP ME I AM MAKING A HANGMAN GAME THIS IS MY SCHOOL PROJECT AND I HAVE TO SUMBIT IT TOMMOROW AND I AM GETTING A ERROR IN MY CODE
Exception in thread «AWT-EventQueue-0» java.lang.NullPointerException
at HangmanGameFrame.<init>(HangmanGameFrame.java:24)
at HangmanGameFrame$5.run(HangmanGameFrame.java:447)
What I have tried:
HERE IS MY CODE
import java.io.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
/**
*
* @author Muhammmad Kashif
*/
public class HangmanGameFrame extends javax.swing.JFrame {
char c;
String pass;
String[] words=readArray(«words.txt»);
Random rn=new Random();
int randomNumber = rn.nextInt(words.length);
String answer;
int numberofMisses=0;
String rightorWrong;
ArrayList<string> letterArrayList=new ArrayList<>();
int numberofBlank;
ImageIcon hang=new ImageIcon(«First.png»);
ImageIcon hang1=new ImageIcon(«Second.png»);
ImageIcon hang2=new ImageIcon(«Third.png»);
ImageIcon hang3=new ImageIcon(«Fourth.png»);
ImageIcon hang4=new ImageIcon(«Fifth.png»);
ImageIcon hangdead=new ImageIcon(«First.png»);
public HangmanGameFrame() {
initComponents();
getContentPane().setBackground(Color.WHITE);
wrongwords.setText(null);
answer = words[randomNumber];
answer = answer.toUpperCase();
StringBuilder tempDisplayAnswer= new StringBuilder(answer);
for(int x=0; x<=answer.length()-1;x++)
{
tempDisplayAnswer.setCharAt(x,’-‘);
String displayAnswer=tempDisplayAnswer.toString();
labelword.setText(displayAnswer);
}
hangman.setIcon(hang);
exit.setVisible(false);
Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.size().width/2,dim.height/2-this.getSize().height/2);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings(«unchecked»)
// <editor-fold defaultstate=»collapsed» desc=»Generated Code»>
private void initComponents() {
conform = new java.awt.Button();
exit = new javax.swing.JButton();
hangman = new javax.swing.JLabel();
labelword = new javax.swing.JLabel();
inputtext = new javax.swing.JTextField();
outputtext = new javax.swing.JTextField();
infoNOofMisses = new javax.swing.JLabel();
labOutputNoOfMisses = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
wrongwords = new javax.swing.JTextArea();
tryagain1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
conform.setLabel(«CONFORM!»);
conform.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
conformActionPerformed(evt);
}
});
exit.setText(«EXIT»);
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
}
});
labelword.setFont(new java.awt.Font(«Tahoma», 1, 60)); // NOI18N
labelword.setText(«- — — «);
inputtext.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
inputtextKeyTyped(evt);
}
});
infoNOofMisses.setText(«No. Of Misses:»);
wrongwords.setColumns(20);
wrongwords.setRows(5);
jScrollPane1.setViewportView(wrongwords);
tryagain1.setText(«TRY AGAIN!»);
tryagain1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tryagain1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(32, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(infoNOofMisses, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(labOutputNoOfMisses, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51)
.addComponent(labelword)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(hangman, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(221, 221, 221))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(conform, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(101, 101, 101)
.addComponent(exit, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(59, 59, 59))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(157, 157, 157)
.addComponent(inputtext, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(tryagain1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40))))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(outputtext, javax.swing.GroupLayout.PREFERRED_SIZE, 628, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(hangman, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(58, 58, 58)
.addComponent(tryagain1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(39, 39, 39))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(labOutputNoOfMisses, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(77, 77, 77)
.addComponent(labelword, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(infoNOofMisses, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addGap(18, 18, 18)
.addComponent(inputtext, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(133, 133, 133)))
.addComponent(outputtext, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(conform, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(exit, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
pack();
}//
public static String[] readArray(String file){
//step 1: Count How many Lines
// Step2: Create array and copy the elements in.
int ctr=0;
try{
Scanner s1=new Scanner(new File(file));
while(s1.hasNextLine())
{
ctr=ctr+1;
s1.next();
}
String[] words=new String[ctr];
Scanner s2=new Scanner(new File(file));
for(int i=0;i<ctr;i++)
{
words[i]=s2.next();
}
return words;
}
catch(FileNotFoundException e)
{
return null;}
}
static public int SortedLinearSearch(String [] A,String B)
{
for(int k=0;k<A.length;k++)
{
if(A[k].equals(B))
{
return k;
}
}
return -1;
}
private void exitActionPerformed(java.awt.event.ActionEvent evt) {
HangmanGameFrame.this.dispose();
}
private void conformActionPerformed(java.awt.event.ActionEvent evt) {
numberofBlank=(labelword.getText()).length();
String b=inputtext.getText();
for(int x=0;x<=answer.length()-1;x++){ //add char of the answer to «LetterArrayList»
letterArrayList.add(String.valueOf(answer.charAt(x)));
}
String[] letter=new String[answer.length()];
for(int x=0;x<answer.length()-1;x++) // Convert Array List To Array
{
letter[x]=letterArrayList.get(x);
}
if(numberofMisses<6)// error trapping for blank inputbox
{
if(wrongwords.getText().equals(«»)){
pass=»yes»;
}
else{
pass=»no»;
}
if(inputtext.getText().equals(«»))
{
outputtext.setText(«Please Give Me A Letter! «);
}
if(!inputtext.getText().equals(«»)){
for(int x=0;x<=(wrongwords.getText()).length()-1;x++)
{
char WrongLetter=(wrongwords.getText()).charAt(x); //determine wheather key is repeated or not
if((inputtext.getText()).charAt(0) != WrongLetter){
pass=»yes»;
}
else if((inputtext.getText()).charAt(0)== WrongLetter){
pass=»no»;
outputtext.setText(«This Letter Is Already Used»);
break;
}
}}
if(pass==»YES»){
if(Character.isLetter(c)){
if(SortedLinearSearch(letter,b)== -1){
wrongwords.setText(wrongwords.getText()+String.valueOf(inputtext.getText())+» «);
//For Audios
InputStream in;
try{
in=new FileInputStream(new File(«»));
AudioStream audios=new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
///////////
for(int x=0;x<wrongwords.getText().length()-1;x++)
{
if(Character.isLetter((wrongwords.getText()).charAt(x))){
numberofMisses++;
break;
}
}
}
}
}
inputtext.setText(null);
}
//change image of Hangman
if(numberofMisses==1)
{
hangman.setIcon(hang);
}
else if(numberofMisses==2)
{
hangman.setIcon(hang1);
}
else if(numberofMisses==3)
{
hangman.setIcon(hang2);
}
else if(numberofMisses==4)
{
hangman.setIcon(hang3);
}
else if(numberofMisses==5)
{
hangman.setIcon(hang4);
}
if(numberofMisses == 6) //loosing condition
{
hangman.setIcon(hangdead);
outputtext.setText(«You Lost !»);
inputtext.setEnabled(false);
conform.setEnabled(false);
exit.setEnabled(true);
////// AUDIO
InputStream in;
try{
in=new FileInputStream(new File(«»));
AudioStream audios=new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch (Exception e){
JOptionPane.showMessageDialog(null,e);
}
////////////////////////////////////////////////////////////////
}
if(SortedLinearSearch(letter,b)!=-1){
StringBuilder tempWord=new StringBuilder(labelword.getText());
tempWord.setCharAt(SortedLinearSearch(letter,b),letter[SortedLinearSearch(letter,b)].charAt(0));
String displayAnswer=tempWord.toString();
labelword.setText(displayAnswer);
//////audio
InputStream in;
try{
in=new FileInputStream(new File(«»));
AudioStream audios=new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch (Exception e){
JOptionPane.showMessageDialog(null,e);
}
///////////////////////////////////
}
for(int x=0;x<=labelword.getText().length()-1;x++)
{
if(((labelword.getText()).charAt(x)) != ‘-‘){
numberofBlank—; //count number Of blanks in labelword
}
}
if(numberofBlank ==0){
conform.setEnabled(false);//if no label — player wins
outputtext.setText(«Hurray! You Won»);
exit.setVisible(true);
InputStream in;
try{
in=new FileInputStream(new File(«»));
AudioStream audios=new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch (Exception e){
JOptionPane.showMessageDialog(null,e);
}
///////////////////////////
}
labOutputNoOfMisses.setText(String.valueOf(numberofMisses));
}
private void inputtextKeyTyped(java.awt.event.KeyEvent evt) {
if(numberofMisses<6){
c=evt.getKeyChar();
if(!(Character.isLetter(c))){
outputtext.setText(«A Letter Please»);
evt.consume();
inputtext.setText(«»);
}
else{
if(inputtext.getText()!=null){
inputtext.setText(null);
outputtext.setText(«»);
}
if(Character.isLowerCase(c)){
evt.setKeyChar(Character.toUpperCase(c));
}}
}
}
private void tryagain1ActionPerformed(java.awt.event.ActionEvent evt) {
this.setVisible(false);
new HangmanGameFrame().setVisible(true); //this will refresh page
///////////audio
InputStream in;
try{
in=new FileInputStream(new File(«»));
AudioStream audios=new AudioStream(in);
AudioPlayer.player.start(audios);
}
catch (Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate=»collapsed» desc=» Look and feel setting code (optional) «>
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if («Nimbus».equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(HangmanGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(HangmanGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(HangmanGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(HangmanGameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new HangmanGameFrame().setVisible(true);
}
});
}
// Variables declaration — do not modify
private java.awt.Button conform;
private javax.swing.JButton exit;
private javax.swing.JLabel hangman;
private javax.swing.JLabel infoNOofMisses;
private javax.swing.JTextField inputtext;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel labOutputNoOfMisses;
private javax.swing.JLabel labelword;
private javax.swing.JTextField outputtext;
private javax.swing.JButton tryagain1;
private javax.swing.JTextArea wrongwords;
// End of variables declaration
static class setVisible{
public setVisible(boolean b){
}
}
}
Recommended Answers
If you read the messages they tell you at which line you get the error and what the error is.
You are using something which is null
Jump to Post
Hi,
It seems that you are setting a null model for ComboBox in your
initComponents()method (which is not listed in the code you’ve shown us).
Check your code at line 292 as shown in the error log.… and next time please use [code] tags for your code
GL
Jump to Post
A NullPointerException is
Thrown when an application attempts to use null in a case where an object is required. These include:
* Calling the instance method of a null object.
* Accessing or modifying the field of a null object.
* Taking the length of null as if it were …
Jump to Post
Why are you talking about editing the «fixed Java classes»? The error is in your code. The error messages relate to a single error and show the sequence of calls (starting deep in the Swing event handler), via your faulty code, and maybe back into a Java API method before …
Jump to Post
All 14 Replies
javaAddict
900
Nearly a Senior Poster
Team Colleague
Featured Poster
13 Years Ago
If you read the messages they tell you at which line you get the error and what the error is.
You are using something which is null
13 Years Ago
yeah i am unable to locate the thing that is null, and the errors are inside the java fixed classes which i have in no way edited.
here is the syntax from my mainGUI. does it show where the NullPointer is?
package Application;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileInputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.helpers.DefaultHandler;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import Assingment.User;
import Assingment.NormalUser;
import Assingment.AdminUser;
import Assingment.UserList;
import Assingment.BusinessManager;
import Assingment.UserHandler;
/**
*
* @author Tristan
*/
public class UserManagement extends javax.swing.JFrame {
private BusinessManager theBM;
private UserList users;
private AdminUser adminUsers;
private NormalUser normalUsers;
private DefaultComboBoxModel userModel;
private File fileName;
private String[] userNames;
/** Creates new form UserManagement */
public UserManagement() {
createDM();
createUserCmb();
initComponents();
// Create the File object to hold the file name
fileName = new File("C:\Users\Tristan\Desktop\edited\Assingment 2010-01-16 at 16.11.38", "UserData.xml");
// Create the data in a Branch object, then get the
// account numbers and place them in the combo box.
getData();
userNames = users.getUserNames();
userModel = new DefaultComboBoxModel(userNames);
// NetBeans method to initialise GUI components
// Show the data for the first Users
cmbUsers.setSelectedIndex(0);
showUsersDetails();
}
private void getData() {
// Set up the file details and create the parser, then start it.
// On completion, retrieve the accounts and display them.
DefaultHandler handler = new UserHandler();
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(fileName, handler);
} catch (Exception err) {
System.out.println("Exception: " + err.getMessage());
err.printStackTrace();
}
// On completion of the parsing process, get the branch object
// created by the account handler
users = ((UserHandler) handler).getUserlist();
}
private void createDM() {
// Creates the model through test data
generateTD();
}
private void createUserCmb() {
String[] userNames = users.getUserNames();
userModel = new DefaultComboBoxModel(userNames);
}
private void generateTD() {
// This method creates the data model from hard-coded test data.
NormalUser nUser;
AdminUser aUser;
// Create the object that controls the data model
theBM = new BusinessManager();
// allows the GUI to access the objects they contain.
users = theBM.getUsers();
aUser = new AdminUser("Tristan Parker", "taparker", "tristan@parker.com", 2);
users.addUser(aUser);
nUser = new NormalUser("Caroline Williams", "cmwillaims", "caroline@williams.com", 2);
users.addUser(nUser);
}
// Event Handlers
private void showUsersDetails() {
User selected = users.getUserAt(cmbUsers.getSelectedIndex());
txtEmailAddress.setText(selected.getEmail());
txtUsername.setText(selected.getUserID());
if (selected instanceof AdminUser) {
radAdmin.setSelected(true);
} else {
radNormal.setSelected(true);
}
}
private void addUserDetails() {
AddUserGUI createUser;
User user;
user =new AdminUser();
user =new NormalUser();
createUser =new AddUserGUI(this, true, user);
createUser.setVisible(true);
if (createUser.getCloseButton().equals("OK")) {
users.addUser(user);
userModel.addElement(user.getName());
cmbUsers.setSelectedIndex(users.size() - 1);
}
}
private void updateUser() {
int selectedIndex = cmbUsers.getSelectedIndex();
if (selectedIndex == -1) {
JOptionPane.showMessageDialog(null,
"User not selected!", "Error",
JOptionPane.ERROR_MESSAGE);
} else {
AddUserGUI augUpdate;
User selected = users.getUserAt(selectedIndex);
augUpdate =
new AddUserGUI(this, true, selected);
augUpdate.setVisible(true);
// On return from the dialog, rebuild model in case
// the name has changed
if (augUpdate.getCloseButton().equals("OK")) {
userModel = new DefaultComboBoxModel(users.getUserNames());
cmbUsers.setModel(userModel);
cmbUsers.setSelectedIndex(selectedIndex);
}
}
}
private void deleteUser() {
int confirmed = JOptionPane.showConfirmDialog(null,
"Are you sure you want to delete this user ",
"Confirm closure!", JOptionPane.YES_NO_OPTION);
if (confirmed == JOptionPane.YES_OPTION) {
users.removeUserAt(cmbUsers.getSelectedIndex());
userModel.removeElementAt(cmbUsers.getSelectedIndex());
}
}
// Save and exit
private void saveAndExit() {
FileOutputStream outStream;
PrintWriter pw;
User user;
// Create stream and write the DTD
try {
outStream = new FileOutputStream(fileName);
pw = new PrintWriter(outStream);
// write out DTD
pw.println("<?xml version = "1.0" standalone = "yes"?>");
pw.println("<!DOCTYPE Users [");
pw.println(" <!ELEMENT Users (aUser, nUser)+ >");
pw.println(" <!ELEMENT aUser (name, userID, emailAddress) >");
pw.println(" <!ELEMENT nUser (name, userID, emailAddress) >");
pw.println(" <!ELEMENT name (#PCDATA) >");
pw.println(" <!ELEMENT userID (#PCDATA) >");
pw.println(" <!ELEMENT emailAddress (#PCDATA) >");
pw.println("] >");
// Write out the data
pw.println("<Users>");
// Write out the xml representation of each account object.
// It doesn't matter which type of account it is - because
// BankAccount has a getXML() method as well as the sub-classes
// having the same signature methods, it will use whichever is
// appropriate to the current object.
for (int ct = 0; ct < users.size(); ct++) {
user = users.getUserAt(ct);
pw.println(user.getXML());
}
pw.println("</Users>");
// Close the file
pw.close();
} catch (IOException err) {
err.printStackTrace();
}
// Finally, close the program.
System.exit(0);
}
Edited
13 Years Ago
by peter_budo because:
Keep it Organized — For easy readability, always wrap programming code within posts in [code] (code blocks)
AndreiDMS
0
Junior Poster in Training
13 Years Ago
Hi,
It seems that you are setting a null model for ComboBox in your initComponents() method (which is not listed in the code you’ve shown us).
Check your code at line 292 as shown in the error log.
… and next time please use [code] tags for your code
GL
Edited
10 Years Ago
by happygeek because:
fixed formatting
13 Years Ago
now i am getting a new set of error codes, i am unable to edit anything within the fixed java classes.
Exception in thread «AWT-EventQueue-0» java.lang.NullPointerException
at Application.UserManagement.showUsersDetails(UserManagement.java:121)
at Application.UserManagement.cmbUsersClicked(UserManagement.java:449)
at Application.UserManagement.access$000(UserManagement.java:35)
at Application.UserManagement$1.actionPerformed(UserManagement.java:268)
at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1240)
at javax.swing.JComboBox.setSelectedItem(JComboBox.java:567)
at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:603)
at Application.UserManagement.<init>(UserManagement.java:65)
at Application.UserManagement$7.run(UserManagement.java:479)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
AndreiDMS
0
Junior Poster in Training
13 Years Ago
A NullPointerException is
Thrown when an application attempts to use null in a case where an object is required. These include:
* Calling the instance method of a null object.
* Accessing or modifying the field of a null object.
* Taking the length of null as if it were an array.
* Accessing or modifying the slots of null as if it were an array.
* Throwing null as if it were a Throwable value.
Check your showUserDetails method for one of this cases.
Hope this helps,
GL
JamesCherrill
4,667
Most Valuable Poster
Team Colleague
Featured Poster
13 Years Ago
Why are you talking about editing the «fixed Java classes»? The error is in your code. The error messages relate to a single error and show the sequence of calls (starting deep in the Swing event handler), via your faulty code, and maybe back into a Java API method before the error is detected. However, the fault will be in the few lines of your code that are listed, specifically:
at Application.UserManagement.showUsersDetails(UserManagement.java:121)
Somewhere on that line is an uninitialised variable or a method call that has returned null. If you don’t know which it is, try printing each and every value on that line to System.out
javaAddict
900
Nearly a Senior Poster
Team Colleague
Featured Poster
13 Years Ago
yeah i am unable to locate the thing that is null, and the errors are inside the java fixed classes which i have in no way edited.
No you were too lazy to read the messages, as I told you. That is why you couldn’t locate the error.:
Exception in thread «AWT-EventQueue-0» java.lang.NullPointerException
at javax.swing.JComboBox.setModel(JComboBox.java:292)
at Application.UserManagement.initComponents(UserManagement.java:234)
at Application.UserManagement.<init>(UserManagement.java:52)
at Application.UserManagement$7.run(UserManagement.java:448)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
BUILD SUCCESSFUL (total time: 1 second)
Did I have to point that out to you? When you get any error, don’t you even bother to read it, or just post the error and expect others to do it for you?
If you still can’t fix it, then point out at the code where that line is. Although the problem is that you are using something which is null (you haven’t initialized something) as stated by the exception and other posters:
Exception in thread «AWT-EventQueue-0» java.lang.NullPointerException
13 Years Ago
fileName = new File("C:\Users\Tristan\Desktop\edited\Assingment 2010-01-16 at 16.11.38", "UserData.xml");
might be you were not given correct path for file…
check also ..
some times file will be taken but no contents in it..
so no user from the file means nullpointerexception may come..
xy75
-3
Newbie Poster
12 Years Ago
Just replace simple types like int, long etc. by corresponding class types like Integer, Long etc. It really helps 
Ezzaral
2,714
Posting Sage
Team Colleague
Featured Poster
12 Years Ago
>Just replace simple types like int, long etc. by corresponding class types like Integer, Long etc. It really helps 
Why on Earth did you resurrect this old thread to post such nonsense?
10 Years Ago
I would just like to add a suggestion for those who stumble upon this the way I did. I had the EXACT same error and even with this thread it took me forever to figure out (2 hours actually). I’m a new programmer (can’t really even call me that yet) so forgive any mistakes.
So I had a JButton that I declared at the very top of my code (as instance variable i guess?) and then AGAIN i declared it WITHIN my constructor. Not sure if this is how to word it so I will put an example.
public class Hangman extends JFrame{
private JButton a; //created variable 'a' to refer to a future button.
public Hangman(){
JButton n = new JButton("n"); //then here I put "JButton" again, and aparently didn't need that? Because when I removed JButton from this line, everything went back to normal.
}
//then down here I had another method that was used to set a few properties of n.
I also post this because I don’t fully understand it and would like to know why it did this. I assume that it went out of scope or something, because the action handler that was controlling the ‘a’ button worked great, but the method called later to work on the properties was outside of the method it was created in. The button never left the frame, but aparently no longer existed in memory. Can someone explain this so I understand WHY it happend? I fixed my bug, but would like to know why what I did worked lol. It will help others who stumble upon this because as a newbie, this was actually a tough bug to fix (hope the OP figured his out 2 years ago).
JamesCherrill
4,667
Most Valuable Poster
Team Colleague
Featured Poster
10 Years Ago
Line 3 declares a button variable, but does not initialise it, so it’s null
line 6 declares a second button variable that happens to have the same name, and initialises it to refer to a newly-created button.
At line 7 the second variable goes out of scope and ceases to exist. That leaves the button created on line 6 with no remaining references, so it’s garbage collected.
The rest of the code then executes with the original button variable still null.
10 Years Ago
Crap, I didn’t realize that I put ‘a’ as the first button and ‘n’ as the second. They were both supposed to be ‘a’. I wish I could edit that now!
It seems like you knew what I meant to say though. Thank you for that explanation! I didn’t realize that you could do that. So the only reason it allows me to declare two variables of the same name is because they are in different ‘scopes’? Because normally it tells me «duplicate variable» or something like that. Does declaring it within the method OVERRIDE the old variable? Or does it just create a second pointer to the same object (or lack therof in this case).
10 Years Ago
A field and a local variable that happen to have the same name are otherwise completely unconnected. Only the name is the same. It is much like having a method and a local variable with the same name. As far as the compiler is concerned, it is just a trivial coincidence. The compiler cares no more that a field and variable have the same name than you would care about having the same number of teeth as the number of protons in an atom of germanium.
The only issue is the potential ambiguity about whether you are refering to the field or the variable when you use the name a, and that’s not really ambiguous because the compiler always assumes that you mean the variable. If you want to use the field a in the scope of a local variable named a, you normally do it by typing this.a, since that makes the fact that a is a field explicit. Naturally you can use this every time you access a field of this, and leaving this off is just a conveninent abbreviation that unfortunately causes some confusion as in this case. JavaScript and Python are examples of languages that requires this every time, and if you want to do that in Java it would be hard to call you wrong since it allows anyone reading your source code to instantly distinguish fields from local variables.
Edited
10 Years Ago
by bguild
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
У меня выскакивает в конце ошибка
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError.
в строке —
at game.View.paint(View.java:39)
package com.javarush.task.task35.task3513;
import javax.swing.*;
import java.awt.*;
public class View extends JPanel {
private static final Color BG_COLOR = new Color(0xbbada0);
private static final String FONT_NAME = "Arial";
private static final int TILE_SIZE = 96;
private static final int TILE_MARGIN = 12;
private Controller controller;
boolean isGameWon = false;
boolean isGameLost = false;
public View(Controller controller) {
setFocusable(true);
this.controller = controller;
addKeyListener(controller);
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(BG_COLOR);
g.fillRect(0, 0, this.getSize().width, this.getSize().height);
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) {
drawTile(g, controller.getGameTiles()[y][x], x, y);
}
}
g.drawString("Score: " + controller.getScore(), 140, 465);
if (isGameWon) {
JOptionPane.showMessageDialog(this, "You've won!");
} else if(isGameLost) {
JOptionPane.showMessageDialog(this, "You've lost :(");
}
}
private void drawTile(Graphics g2, Tile tile, int x, int y) {
Graphics2D g = ((Graphics2D) g2);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int value = tile.value;
int xOffset = offsetCoors(x);
int yOffset = offsetCoors(y);
g.setColor(tile.getTileColor());
g.fillRoundRect(xOffset, yOffset, TILE_SIZE, TILE_SIZE , 8, 8);
g.setColor(tile.getFontColor());
final int size = value < 100 ? 36 : value < 1000 ? 32 : 24;
final Font font = new Font(FONT_NAME, Font.BOLD, size);
g.setFont(font);
String s = String.valueOf(value);
final FontMetrics fm = getFontMetrics(font);
final int w = fm.stringWidth(s);
final int h = -(int) fm.getLineMetrics(s, g).getBaselineOffsets()[2];
if (value != 0)
g.drawString(s, xOffset + (TILE_SIZE - w) / 2, yOffset + TILE_SIZE - (TILE_SIZE - h) / 2 - 2);
}
private static int offsetCoors(int arg) {
return arg * (TILE_MARGIN + TILE_SIZE) + TILE_MARGIN;
}
}
posted 14 years ago
-
-
Number of slices to send:
Optional ‘thank-you’ note:
-
-
Thanks for that. When I try to execute it I still get the error.
Heres my code and errors:
Errors:
run:
Enter a complex number:
Exception in thread «AWT-EventQueue-0» java.lang.NullPointerException
at ComplexPanel.paintComponent(ComplexNumberPlot.java:67)
at javax.swing.JComponent.paint(JComponent.java:1027)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1036)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1036)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:564)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5129)
at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:277)
at javax.swing.RepaintManager.paint(RepaintManager.java:1217)
at javax.swing.JComponent.paint(JComponent.java:1013)
at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
at java.awt.Container.paint(Container.java:1780)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:814)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:714)
at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:694)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Exception in thread «AWT-EventQueue-0» java.lang.NullPointerException
at ComplexPanel.paintComponent(ComplexNumberPlot.java:67)
at javax.swing.JComponent.paint(JComponent.java:1027)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1036)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paint(JComponent.java:1036)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:564)
at javax.swing.JComponent.paintChildren(JComponent.java:864)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5129)
at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:277)
at javax.swing.RepaintManager.paint(RepaintManager.java:1217)
at javax.swing.JComponent.paint(JComponent.java:1013)
at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
at java.awt.Container.paint(Container.java:1780)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:814)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:714)
at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:694)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:128)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
BUILD SUCCESSFUL (total time: 19 seconds)
and if you need it, my class that represents complex numbers:
Exception in thread «AWT-EventQueue-0» java.lang.NullPointerException using CreateTable() / Java
Hi,
Is there anyone here who is using the Yair’s CreateTable() function.
I used this function to embed two java tables into my GUI. I didn’t use the standard GUI uitable simply because the latter one provides me more flexibitlies.
But if I close my GUI, then I get two red java errors in workspace, in format:
Exception in thread «AWT-EventQueue-0» java.lang.NullPointerException at com.mathworks.widgets.spreadsheet.SpreadsheetScrollPane.cleanup(SpreadsheetScrollPane.java:571) at com.mathworks.hg.peer.UitablePeer$3.run(UitablePeer.java:149) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(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)
Does anyone have a idea why this happens and how to solve this ?
By the way, I am not a java experts. How can I find out all the methods within a java (like jTable) object?
Thanks
Answers (6)
I have a solution for that don’t bother about that ..whenever encounter this type of error in matlab command window just you have to write this code ,which is shown in below…
opengl(‘save’,’software’)
and then run the program again you have encounter same error …
and then you just close matlab window and then open matlab freshly…
after that you run the program and code will be executed with out any errors…..
thank you…..
if you have any doubts please contact me via email….
this is my email id : venkydhoni2@gmail.com
I get this same error, and most of the time MATLAB locks up. It generally happens when MATLAB is open overnight. I have never seen it while I am working. This should be looked at by tech support as I have lost data during big overnight runs.
I too have the same problem can some one support me also
I am going to try adding this to my code to catch the error before it crashes my program. It only happens when I leave it running all night.
%Have some Java javaControl = javaObjectEDT(‘javax.swing.JFrame’); pause(0.05); drawnow; % this never hurt anyone! fprintf(‘ b’);
What worked for me was to replace the line
tab.TableScrollPane.setRowHeader(»);
with
tab.TableScrollPane.setRowHeaderView(javax.swing.JLabel(»))
Then no more «AWT-EventQueue-0» exceptions when closing the uitable.




