Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

Hi, I am a new programmer at the high school level, so I know little about programming and get quite a lot of errors that have been resolved, while others I do not understand at all. I have to make a simple Check Box selection program where the user can choose between different selection options and change the image depending on their action. The program itself compiles fine, but when I run it, it gives me some complications. Here is my program:

 package components; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Workshop extends JPanel implements ItemListener { JCheckBox winterhatButton; JCheckBox sportshatButton; JCheckBox santahatButton; JCheckBox redshirtButton; JCheckBox brownshirtButton; JCheckBox suitButton; JCheckBox denimjeansButton; JCheckBox blackpantsButton; JCheckBox khakipantsButton; StringBuffer choices; JLabel pictureLabel; public Workshop() { super(new BorderLayout()); //Create the check boxes. winterhatButton = new JCheckBox("Winter Hat"); winterhatButton.setMnemonic(KeyEvent.VK_Q); sportshatButton = new JCheckBox("Sports Hat"); sportshatButton.setMnemonic(KeyEvent.VK_W); santahatButton = new JCheckBox("Santa hat"); santahatButton.setMnemonic(KeyEvent.VK_E); redshirtButton = new JCheckBox("Red Shirt"); redshirtButton.setMnemonic(KeyEvent.VK_R); brownshirtButton = new JCheckBox("Brown Shirt"); brownshirtButton.setMnemonic(KeyEvent.VK_T); suitButton = new JCheckBox("Suit"); suitButton.setMnemonic(KeyEvent.VK_Y); suitButton = new JCheckBox("Denim Jeans"); suitButton.setMnemonic(KeyEvent.VK_U); blackpantsButton = new JCheckBox("Black Pants"); blackpantsButton.setMnemonic(KeyEvent.VK_I); khakipantsButton = new JCheckBox("Khaki Pants"); khakipantsButton.setMnemonic(KeyEvent.VK_O); //Register a listener for the check boxes. winterhatButton.addItemListener(this); sportshatButton.addItemListener(this); santahatButton.addItemListener(this); redshirtButton.addItemListener(this); brownshirtButton.addItemListener(this); suitButton.addItemListener(this); denimjeansButton.addItemListener(this); blackpantsButton.addItemListener(this); khakipantsButton.addItemListener(this); //Indicates choices = new StringBuffer("---------"); //Set up the picture label pictureLabel = new JLabel(); pictureLabel.setFont(pictureLabel.getFont().deriveFont(Font.ITALIC)); updatePicture(); //Put the check boxes in a column in a panel JPanel checkPanel = new JPanel(new GridLayout(0, 1)); checkPanel.add(winterhatButton); checkPanel.add(sportshatButton); checkPanel.add(santahatButton); checkPanel.add(redshirtButton); checkPanel.add(brownshirtButton); checkPanel.add(suitButton); checkPanel.add(denimjeansButton); checkPanel.add(blackpantsButton); checkPanel.add(khakipantsButton); add(checkPanel, BorderLayout.LINE_START); add(pictureLabel, BorderLayout.CENTER); setBorder(BorderFactory.createEmptyBorder(20,20,20,20)); } /** Listens to the check boxes. */ public void itemStateChanged(ItemEvent e) { int index = 0; char c = '-'; Object source = e.getItemSelectable(); if (source == winterhatButton) { index = 0; c = 'q'; } else if (source == sportshatButton) { index = 1; c = 'w'; } else if (source == santahatButton) { index = 2; c = 'e'; } else if (source == redshirtButton) { index = 3; c = 'r'; } else if (source == brownshirtButton) { index = 4; c = 't'; } else if (source == suitButton) { index = 5; c = 'y'; } else if (source == denimjeansButton) { index = 6; c = 'u'; } else if (source == blackpantsButton) { index = 7; c = 'i'; } else if (source == khakipantsButton) { index = 8; c = 'o'; } if (e.getStateChange() == ItemEvent.DESELECTED) { c = '-'; } //Apply the change to the string. choices.setCharAt(index, c); updatePicture(); } protected void updatePicture() { //Get the icon corresponding to the image. ImageIcon icon = createImageIcon( "images/bear/bear-" + choices.toString() + ".gif"); pictureLabel.setIcon(icon); pictureLabel.setToolTipText(choices.toString()); if (icon == null) { pictureLabel.setText("Missing Image"); } else { pictureLabel.setText(null); } } /** Returns an ImageIcon, or null if the path was invalid. */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = Workshop.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn't find file: " + path); return null; } } private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("Build a Bear at Safeer Workshop!"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. JComponent newContentPane = new Workshop(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } 

Well to this part it works smoothly and is consistent, but when I start running the program, I get this error.

 > run components.Workshop Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at components.Workshop.<init>(Workshop.java:75) at components.Workshop.createAndShowGUI(Workshop.java:195) at components.Workshop.access$0(Workshop.java:189) at components.Workshop$1.run(Workshop.java:209) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$000(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.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) 

This may be a stupid mistake, but I can't figure it out. Please help and thanks.

  Here is the line that generates that error private void jButtonSendActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: String message; if(messageBox.getText().length() > 0){ message = messageBox.getText(); chatBox.append(message+"\n"); printStream.println(message);//this line printStream.flush(); //printStream.close(); messageBox.setText(""); } } 
+8
nullpointerexception runtime-error drjava
source share
3 answers

NullPointerException are some of the easiest diagnostic exceptions often. Whenever you get an exception in Java and you see a stack trace (which, by the way, is your second quotation block), you read from top to bottom. Often you will see exceptions that start in the Java library code or in your own implementation methods, for diagnostics you can simply skip them until you see the code file that you wrote.

Then you will like the specified line and look at each of the objects (created by the class instances) on this line - one of them was not created, and you tried to use it. You can start by searching in your code to see if you called the constructor on this object. If you did not do this, then your problem is, you need to create an instance of this object by calling the new class name (arguments). Another common reason for a NullPointerException is that it accidentally declares an object with a local scope when there is an instance variable with the same name.

In your case, an exception occurred in your constructor for Workshop on line 75. <init> means the constructor for the class. If you look at this line in your code, you will see the line

 denimjeansButton.addItemListener(this); 

Two objects are pretty clear on this line: denimjeansButton and this . this is a synonym for the class instance that you are currently in and you are in the constructor, so it cannot be this . denimjeansButton is your culprit. You have never created an instance of this object. Either remove the reference to the denimjeansButton instance denimjeansButton , or create one.

+23
source share

At the top of the code with Public Workshop (), I assume that this bit,

 suitButton = new JCheckBox("Suit"); suitButton.setMnemonic(KeyEvent.VK_Y); suitButton = new JCheckBox("Denim Jeans"); suitButton.setMnemonic(KeyEvent.VK_U); 

may be,

 suitButton = new JCheckBox("Suit"); suitButton.setMnemonic(KeyEvent.VK_Y); denimjeansButton = new JCheckBox("Denim Jeans"); denimjeansButton.setMnemonic(KeyEvent.VK_U); 
0
source share
 if(verifyFields()) { try { if(!checkUsername(usrname)) { Connection conn = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/amazingrestaurant", "root", ""); } catch (SQLException ex) { Logger.getLogger(RegistrationForm.class.getName()).log(Level.SEVERE, null, ex); } PreparedStatement stmt; ResultSet rs; String registerUserQuery = "INSERT INTO 'loginregister'('firstname', 'lastname', 'username', 'gender', 'dateofbirth', 'phone', 'address', 'suburb', 'postcode', 'state', 'password') VALUES (?,?,?,?,?,?,?,?,?,?,?)"; try { stmt = conn.prepareStatement(registerUserQuery); stmt.setString(1, fname); stmt.setString(2, lname); stmt.setString(3, gender); stmt.setString(4, dob); stmt.setString(5, phone); stmt.setString(6, address); stmt.setString(7, suburb); stmt.setString(8, postcode); stmt.setString(9, state); stmt.setString(10, psw); if(stmt.executeUpdate()!= 0){ JOptionPane.showMessageDialog(null,"Your account has been created successfully"); } else { JOptionPane.showMessageDialog(null, "Error: Check your information"); } } catch (SQLException ex) { Logger.getLogger(RegistrationForm.class.getName()).log(Level.SEVERE, null, ex); } } } catch (SQLException ex) { Logger.getLogger(RegistrationForm.class.getName()).log(Level.SEVERE, null, ex); } } } 

Can someone help me get rid of nullpointerexception here

 xception in thread "AWT-EventQueue-0" java.lang.NullPointerException at EmployeeAccess.RegistrationForm.verifyFields(RegistrationForm.java:487) at EmployeeAccess.RegistrationForm.jButton_signupActionPerformed(RegistrationForm.java:413) at EmployeeAccess.RegistrationForm$4.actionPerformed(RegistrationForm.java:250) 
0
source share

All Articles