user3433599
user3433599

Reputation:

How to add multiple classes to a single JFrame?

So I'm trying to add multiple classes to my JFrame 'frame' using a JPanel 'panel' but it doesn't seem to have any effect. Here's my main class:

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Frame
{
    public static void main (String[] args)
    {
        JPanel panel = new JPanel();
        panel.setBackground (Color.WHITE);
        panel.add (new Player()); // Class with paintComponent method.
        panel.add (new Terrain()); // Class with paintComponent method.

        JFrame frame = new JFrame ("Java Game");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setSize (1000, 600);
        frame.getContentPane().add (panel);
        frame.setVisible (true);
    }
}

When I run the program, the JFrame appears with a white background, but the paintComponent methods from the Player and Terrain classes aren't being called, so nothing else is being rendered. Is there anything wrong with this code? Thanks.

Edit: Here are my Player and Terrain classes:

Player:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;

@SuppressWarnings ("serial")
public class Player extends JComponent
{
    int x = 50;
    int y = 450;

    public void paintComponent (Graphics graphics)
    {
        graphics.setColor (Color.BLACK);
        graphics.fillRect (x, y, 50, 50);
    }
}

Terrain:

import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JComponent;

@SuppressWarnings ("serial")
public class Terrain extends JComponent
{
    Player playerClass = new Player();

    public void paintComponent (Graphics graphics)
    {
        graphics.setColor (Color.GREEN);
        graphics.fillRect (0, 500, 1000, 500);
    }
}

Upvotes: 0

Views: 1759

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

  1. You've failed to override getPreferredSize of Player and Terrain, causing them to be laid out at their default size of 0x0
  2. You've broken the paint chain by not calling super.paintComponent, which could cause no end of painting issues and artifacts
  3. The reference of Player in Terrain has nothing to do with the reference on the screen

Take a look at Laying Out Components Within a Container, Painting in AWT and Swing and Performing Custom Painting for more details

Upvotes: 2

Related Questions