I am trying to add a value and display it on a progress bar i have created on a jframe through my main (because i have methods left and right and i want that value to be from 1 of theses) but when i run it it gives me
Exception in thread "main" java.lang.NullPointerException
i understand that i have to initialize the "var" so I wont be getting that error but i dont really know how. (i am kind of new to java)
This is my code (there are probably unnecessary stuff here but they were created automatically through the design)
import java.io.IOException;
public class UI extends javax.swing.JFrame {
/**
* Creates new form UI
*/
public UI() {
initComponents();
}
/**
* 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() {
p1hp = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(p1hp, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(768, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(469, Short.MAX_VALUE)
.addComponent(p1hp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(100, 100, 100))
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new UI().setVisible(true);
}
});
// THIS IS WHAT I AM TRYING TO DO
p1hp.setStringPainted(true);
p1hp.setValue(12);
}
// Variables declaration - do not modify
public static javax.swing.JProgressBar p1hp;
// End of variables declaration
}
aside that though, i tried creating a button, which i added thoses 2 lines and it worked fine
(the code for the button isnt here)
Note1: I manually maked the progressbar static bacause if not, I would get the error
non-static variable p1hp cannot be referenced from a static context
Note2: I have read this answer:
What is a NullPointerException, and how do I fix it?
Still not sure how to fix it
Note3: I am using Netbeans 8.2