JComponent added to JPanel doesn't appear?

21 Views Asked by At

I have searched a lot for this problem and did find similar problems but not exactly this so nothing has worked yet.

I am making a game like Vampire Survivors and right now I am trying to get the playable character to appear on the screen.

My method is to create a JPanel that has a picture and is essentially the background. Then I add the HeroComponent over it and also the MonstersComponent (still on the hero part).

The way it works is that the player should always be in the middle of the screen and when he moves right, the background JPanel and all the monsters will move the opposite direction giving the "illusion" of movement.

However, when I add the playerComponent to the JPanel, the Hero doesn't appear. The majority of stuff is divided into files to make it easier but when I add the HeroComponent to the JFrame it does work normally.

These are my relevant files:

The file for creating the JFrame and adding the JPanel:

public class GameWindow {
    private JFrame frame;
    private Hero hero;
    private GameBackgroundPanel backgroundPanel;

    public GameWindow(JFrame frame, Hero hero) {
        this.frame = frame;
        this.hero = hero;
        backgroundPanel = new GameBackgroundPanel();
//        frame.add(backgroundPanel, BorderLayout.CENTER);

        frame.setLayout(new BorderLayout());
        frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setUndecorated(true);
        frame.setResizable(false);

        frame.setContentPane(backgroundPanel);
    }

    public void startWindow() {
        frame.setVisible(true);
    }
}

The file for creating the JPanel and adding the component(s) to it:

    public class GameBackgroundPanel extends JPanel {
    public int backgroundX = 0, backgroundY = 0;
    private ImageIcon icon = new ImageIcon("src/se/liu/rodis915/mineIsAPicture/poggers.png");
    private Hero hero = new HeroA();

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
//        Graphics2D g2d = (Graphics2D)g;
        HeroToComponent heroComponent = new HeroToComponent(hero);
        setLayout(new FlowLayout());
        setOpaque(false);
        g.drawImage(icon.getImage(), backgroundX, backgroundY, getWidth(), getWidth(), null);
        add(heroComponent, BorderLayout.CENTER);
    }
}

I assume it's something with the Layout of the JPanel, the order code lines or something of the sort.

I would also appreciate opinions about the movement idea; if I move the JPanel position, will everything inside also follow along? If yes, how would I achieve that goal? I was hopping to just add components to the JFrame but I can't add more than 1 so I'm kinda lost.

Thanks so much!

0

There are 0 best solutions below