The Biggest problem you have is improperly/incorrectly/unnecessarily using inheritance. You think that just because RoomSystem
extends MainSystem
, that the roomPanel
will be shared between the two classes. It doesn't work like that. So roomPanel
in the MainSystem
is never initialized, which is causing the NullPointerException
You need to rethink your class design, and without using inheritance, because it doesn't look like you know how to use it correctly, and because it is not appropriate.
But just yo explain to you what's going on.
You have RoomSystem
, which extends MainSystem
. So RoomSystem
is it's own entity, but has (not share) the same properties and method at MainSystem
, but they have absolutely no relation in terms of object references. So when you call setRoomPanel(new JPanel());
in the RoomSystem
, you are only setting the roomPanel
in the RoomSystem
class, not the MainSystem
class.
A static
field roomPanel
, may seem like the correct fix for beginners, but it's totally inappropriate. If you want RoomSystem
to be it's own panel, then you should make it extends Panel
, and not MainSystem
, and you can just add the RoomSystem
panel to the MainSystem
frame.
If you need to pass something, like the CardLayout
from the MainSystem
to the RoomSystem
, then you can inject it through the constructor.
public class RoomSystem extends JPanel {
private CardLayout;
public RoomSystem(CardLayout layout) {
this.layout = layout;
}
}
Then you can use the layout from the MainSystem
in the RoomSystem
class, as they now reference the same object.
Another design option would be to implement an interface with a method that sets the card (in your MainSystem
class).
public interface CardViewChanger {
public void setCard(String card);
public void previousCard();
}
public class MainSystem extends JFrame implements CardViewChanger {
RoomSystem roomPanel = new RoomSystem(this);
CardLayout layout;
@Override
public void setCard(String card) {
layout.show(this, card);
}
@Override
public void previousCard() {
layout.next();
}
}
public class RoomSystem extends JPanel {
CardViewChanger cardChanger;
public RoomSystem(CardViewChanger cardChanger) {
this.cardChanger = cardChanger;
...
public void actionPerformed(ActionEvent e) {
cardChanger.previousCard();
}
}
}