Value is not transfered from a class to another JAVA - java

I have problems with idS. in sellContainer idS is 1 and in sellCtr is always 0 so the method addItemToSell is not working. Always give null pointer exception.
public class SellCtr{
private SellContainer sellContainer;
private OrderLineSell ols;
private int idS;
private int idOls;
public SellCtr(){
sellContainer = SellContainer.getInstance();
}
public void createSell(String date, Customer c, Employee e){
Sell sell = new Sell(date,c,e);
sellContainer.addSell(sell);
idS = sell.getId();
}
public void addItemToSell(OrderLineSell orderLineSell){
sellContainer.findSell(idS).addOrderLineSell(orderLineSell);
}
public int getId(){
return idS;
}
public int getIdOls(){
return idOls;
}
public Sell findSell(int idS){
return sellContainer.findSell(idS);
}
}
and the other class is :
public class SellContainer{
private ArrayList<Sell> sales;
private static int idS=0;
private static SellContainer instance=null;
public SellContainer(){
sales = new ArrayList<>();
}
public static SellContainer getInstance(){
if(instance == null){
instance = new SellContainer();
}
return instance;
}
public void addSell(Sell s){
idS++;
s.setId(idS);
sales.add(s);
}
public Sell findSell(int idS){
for(Sell sell : sales){
if(sell.getId()==idS){
return sell;
}
}
return null;
}
}
This is the error :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at controlLayer.SellCtr.addItemToSell(SellCtr.java:24)
at tuiLayer.SaleAddItemToSaleGUI$2.actionPerformed(SaleAddItemToSaleGUI.java:93)
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)
I have rebuild the project and the exceptions changed.
EDIT 3 : I have made idS static and now it works. Thanks a lot guys!

I suggest you
make sure you are compiling all your classes. A build tool like maven or gradle will help.
you use enum for singletons. These are thread safe and simpler.
disable the feature in eclipse which allows you to run code which doesn't compile. This only delays finding errors which makes them worse.
I would replace
public class SellContainer{
private ArrayList<Sell> sales;
private static int idS=0;
private static SellContainer instance=null;
public SellContainer(){
sales = new ArrayList<>();
}
public static SellContainer getInstance(){
if(instance == null){
instance = new SellContainer();
}
return instance;
}
with
public enum SellContainer {
INSTANCE;
private final List<Sell> sales = new ArrayList<>();
private int idS = 0;

Initiate the object before the return object is back to the called method.
In SellContainer, if condition failure leads to give back the Sell Object as NULL.
You need to modify this logic.
return null;

Related

How to debug Error(no valid constructor)?

There isn't error until I use writeobject but it keeps give me no valid constructor error, even if I created no-arg constructor and UID, what was the problem in my coding?
Here's an error code in console
java.io.InvalidClassException: AirSwift.Game_player$Player; no valid constructor
at java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(Unknown Source)
at java.io.ObjectStreamClass.checkDeserialize(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at AirSwift.Game_stage.GameLoad(Game_stage.java:168)
at AirSwift.Game_main$7.actionPerformed(Game_main.java:168)
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.AWTEventMulticaster.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$500(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$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.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$JavaSecurityAccessImpl.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)
Here's a class implements Externalizable
public class Player implements Externalizable {
/**
*
*/
private static final long serialVersionUID = 1L;
public int x, y, mode, attackspeed, speed, speedinattack, firecount, hp, mp, time;
public boolean modechanging = false;
public int modechangecount = 0;
Image Player_img = new ImageIcon("Images/Player/Player_0.png").getImage();
Image []Player_Mode_img;
String sound_fire, sound_change;
public Player(){
}
public Player(int hp){
this.ChangeMode(1);
this.hp = hp;
this.mp = 100;
this.x = 100;
this.y = 600;
this.time = 0;
}
Image AnimeMode(){
switch(mode){
case 1:
if(modechangecount < 10) return Player_Mode_img[0];
else if((9<modechangecount)&&(modechangecount<20)) return Player_Mode_img[1];
else return Player_Mode_img[2];
case 2:
return Player_Mode_img[0];
case 3:
if(modechangecount < 10) return Player_Mode_img[0];
else if((9<modechangecount)&&(modechangecount<20)) return Player_Mode_img[1];
else return Player_Mode_img[2];
default: return default_img;
}
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
// TODO Auto-generated method stub
this.x = in.readInt(); this.y = in.readInt(); this.hp = in.readInt(); this.time = in.readInt();
}
public void writeExternal(ObjectOutput out) throws IOException {
// TODO Auto-generated method stub
out.writeInt(this.x); out.writeInt(this.y); out.writeInt(this.hp); out.writeInt(this.time);
}
}
Add default constructor to AirSwift.Game_player as well or declare Player as public static

Storing object in database in Java

I am trying to store my object in MySQL database using java language. I am trying to convert object into byte so I can store it into LONGBLOB. But I am facing error i.e "NotSerializable Exception".
My Class whose object I want to sore:
public class Books implements Serializable {
private int isbn;
private String bookName;
private String author;
private String edition;
private int rowNo;
private int colNo;
private String shelfNo;
private String img;
private InputStream imag;
validation v = new Validation();
Database database;
public Books() { database = new Database(); }
.
.
setters & getters...
Method to call database method to insert object in database:
String className = this.getClass().getName();
database.insertBookRecord(this.getIsbn(), this, className);
this is the object of current class which I want to store.
following is the insertBookRecord method.
public void insertBookRecord(int isbn, Books book, String name) {
String query = "INSERT INTO Test VALUES (?, ?, ?)";
byte[] data = null;
//book = new Books();
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(book);
oos.flush();
oos.close();
baos.close();
data = baos.toByteArray();
}
catch(IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
try {
//conn.setAutoCommit(false);
state = conn.prepareStatement(query);
state.setInt(1, isbn);
state.setString(2, name);
state.setObject(3, data);
state.executeUpdate();
//conn.commit();
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
finally {
close(3);
}
}
When I reach at statement oos.writeObject(book); Its stops with exception and displays the the package & Classname in the JOptionPane.
My book object has all the data fields I entered in the text fields. But I am unable to write it./convert it into Serializable format.
Any suggestions please?
Stack Trace:
java.io.NotSerializableException: com.my.classes.Database
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.my.classes.Database.insertBookRecord(Database.java:123)
at com.my.classes.Books.insertBookRecord(Books.java:107)
at com.my.jlms.ManageBooks$2.actionPerformed(ManageBooks.java:308)
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$500(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$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.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$JavaSecurityAccessImpl.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)
You get the exception because you are trying to serialize an InputStream
private InputStream imag;
InputStream is not Serializable
You could omit this field when serializing by declaring it transient:
private transient InputStream imag;
Your imag is InputStream which is not implement Serializable. It should be a byte[] or String link to your imag location.
Edited: You should separate business from model object. Move insertBook method and database object from Book class to another class.
So the problem was InputStream as well as i was trying to Seralize the objects i.e V & database.
I just added transient e.g private transient Database database; and then declared database = new Database(); in the constructor. hence I was able to serialize it.
Thank you #Ralf, #Joseph, #Diyarbakir and #3kings for helping me out.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException in an implemented node list

I've been searching through my code for hours now, and just can't figure out where this exception occurs.
The program is based on an implemented node list.
Code:
Objectlist class:
public class Billiste{
// Datafelter
private Bil forsteBil;
public Billiste(){
forsteBil = null;
}
public void settInnNyBil(Bil y){
/*if(ny == null){
return;
}*/
System.out.println("fjdklsadkjfldsk");
if(forsteBil == null){
forsteBil = y;
}
else{
Bil løper = forsteBil;
while(løper.nesteBil != null){
løper = løper.nesteBil;
}
løper.nesteBil = y;
}
System.out.println(y);
}
// Metadata om listeobjektene
public String toString() {
String resultat = "";
Bil løper = forsteBil;
while(løper!=null){
resultat += løper.toString() + "\n";
løper = løper.nesteBil;
}
if(!resultat.equals("")){
return resultat;
}else{
return "Ingen biler registrert";
}
}
}// ~Billiste
Object class:
public class Bil {
//Datafelter
private String kjennetegn;
private String merke;
private String type;
Bil nesteBil;
public Bil(String nyK, String nyM, String nyT){
System.out.println("Den får tak i stringene k,m og t - de er ikke null");
kjennetegn = nyK;
merke = nyM;
type = nyT;
nesteBil = null;
System.out.println("Endelse på funksjonen");
}
#Override
public String toString() {
return "Bil [kjennetegn=" + kjennetegn + ", merke=" + merke + ", type="
+ type + ", nesteBil=" + nesteBil + "]";
}
}//~Bil
This is where the error points:
public void nyBil(){
Bil ny = new Bil(regnummertekst.getText(), merke.getText(), type.getText());
bilregister.settInnNyBil(ny);
output.setText(bilregister.toString());
}
And finally the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at BilListeGui.nyBil(BilListeGui.java:79)
at BilListeGui.actionPerformed(BilListeGui.java:86)
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)
I would appreciate all the help I can get.
Thanks in advance
Problem solved, there was no instance of bilregister, thereby giving the error NullPointerException.

Nullpointers in java and how to overcome those?

Say for example, if in a program you get a null-pointer error for adding a piece of code to your which program makes the program run fine but without that piece of code the program doesn't work as expected, would it be a good idea to allow the null-pointer error to happen, if so, is there any way of catching it before it displays onto the console. 1 way I am aware of is, using try and catch but in my past experience this hasn't worked, my attempt at using this might be wrong, but this is how I tried it.
try {
// line / s of code to catch the error from
} catch (java.lang.NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
edited: The list of error i am getting:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at playAGame.endGameResult(playAGame.java:204)
at playAGame.checkingWinner(playAGame.java:159)
at playAGame.callCheckWinner(playAGame.java:179)
at playAGame.moveSetup(playAGame.java:66)
at playAGame$1.actionPerformed(playAGame.java:52)
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.AWTEventMulticaster.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)
this is because of this line: button = new JButton[button.length][button.length];
I am creating a TicTacToe game and if I remove that line from my code, the game won't work properly.
edited: I believe this is one of the lines providing the null pointer, correct me if I am wrong. Basically, I have created a method checking if three given buttons have the value X, if it does then trigger the win variable to true. This is how I am checking if someone has won the TicTacToe game.
public void checkingWinner(JButton button1, JButton button2, JButton button3) {
if(buttonA.getText().equals(buttonB.getText()) && buttonB.getText().equals(buttonC.getText()) && buttonA.getText().equals("X"))
{
win = true;
System.out.pl("winner is X");
}
It's hard to tell without seeing the whole code, but it might be the case that the initialization you're doing of the array is throwing an exception since it's the first time it's being initialized, during which time it is being referenced.
If that's the case, you should solve this by using a constant for the width and height instead of self reference:
public static final int HEIGHT = ...;
public static final int WIDTH = ...;
...
button = new JButton[HEIGHT][WIDTH];
Are you sure that the line/s of code are throwing a NullPointerException? Because it works for me.
public class Main {
static String a;
public static void main(String args[]) {
try {
a.charAt(0);
} catch (java.lang.NullPointerException e) {
System.out.println("Thrown");
e.printStackTrace();
}
}
}

Dispose not working

I'm re-programming one of my old login screen codes and I am changing the:
JPasswordField.getText();
To:
JPasswordFieald.getPassword();
Which is a lot harder because it outputs charecters.
Anyway, JFrame.dispose() isnt working for me. I want my program to dispose an old JFrame to a new JFrame (e.e JFrame2).
Here is my code:
public class Launcher {
//Define Variables
public static String VER = "1.1.0";
public static String STATE = " ALPHA ";
public static JFrame launcher;
public static char[] sPass;
public static String sUser;
//Create widgets
public static JTextField User = new JTextField();
public static JPasswordField Pass = new JPasswordField();
public static JButton Login = new JButton("Login");
//Runs when program starts
public static void main(String[] args) {
NewFrame("Infinite Doom Launcher");
//Checks if login has been pressed
Login.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
sUser = User.getText();
sPass = Pass.getPassword();
//checks if password is correct
if(CheckPass(sPass)) {
if(sUser.equals("genfy")){
Game.main(null);
launcher.dispose();
}
}
}
});
}
//Creates new frame
public static void NewFrame(String Name) {
JFrame launcher = new JFrame(Name + " " + STATE + VER);
launcher.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
launcher.setSize(500,95);
launcher.setResizable(false);
//Add widgets to a Border Layout
launcher.setLayout(new BorderLayout());
launcher.add(User, BorderLayout.NORTH);
launcher.add(Pass, BorderLayout.CENTER);
launcher.add(Login, BorderLayout.SOUTH);
//Set visible
launcher.setVisible(true);
}
//Checks if the entered password is correct
private static boolean CheckPass(char[] input) {
boolean isCorrect = true;
char[] correctPassword = { 'g', 'e', 'n', 'f', 'y', 'g', 'e', 'n', 'y', 's' };
if (input.length != correctPassword.length) {
isCorrect = false;
} else {
isCorrect = Arrays.equals (input, correctPassword);
}
//Zero out the password.
Arrays.fill(correctPassword,'0');
return isCorrect;
}
}
So the problem seems to be occurring at:
//checks if password is correct
if(CheckPass(sPass)) {
if(sUser.equals("genfy")){
Game.main(null);
launcher.dispose();
}
specifically:
launcher.dispose();
So when I press JButton(login) this error appears:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at main.Launcher$1.actionPerformed(Launcher.java:42)
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)
I apologize for my code being so long.
It seems there is a scope problem in NewFrame method at this line:
JFrame launcher = new JFrame(Name + " " + STATE + VER);
This launcher variable is local to NewFrame method and is hidding launcher class member. So when you call launcher.dispose() within actionPerformed() method you get a NullPointerException. To solve this you should do this change:
launcher = new JFrame(Name + " " + STATE + VER);
And also take a look to this topic: The Use of Multiple JFrames, Good/Bad Practice?
Off-topic
As #kleopatra has suggested, learn about java naming conventions and stick to them. See more in this document: Java Code Conventions

Categories