简体   繁体   中英

Drawing from multiple classes to the main class in Java

I'm attempting to create a simple game but I'm running into trouble when drawing from multiple classes in the main class. Here is my code so far.

public static void main(String[] args) 
{
    JFrame mainGameFrame = new JFrame("Space4X");

    StarsPanel starsPanel = new StarsPanel();
    HomePlanet homePlanet = new HomePlanet();

    mainGameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainGameFrame.setResizable(true);

    mainGameFrame.getContentPane().add(homePlanet);
    mainGameFrame.getContentPane().add(starsPanel);


    mainGameFrame.pack();
    mainGameFrame.setVisible(true);

}

public void HomePlanet()
{
  HomePlanet homePlanet = new HomePlanet();

}

}

Here is my HomePlanet class,

package space4x;

import javax.swing.*;
import java.awt.*;

public class HomePlanet extends JPanel 
{


public void HomePlanet()
{

}


public void paintComponent (Graphics page)
{   
    //Draw planet
    super.paintComponent (page);
    page.setColor(Color.RED);
    page.fillRect(10,10,50,50);

}


}

I also have a class called StarsPanel that draws stars in random locations and it works perfectly, but HomePlanet for some reason won't.

Under the mainclass, if I have

mainGameFrame.getContentPane().add(starsPanel);

first instead of starsPanel, it will draw what is under the HomePlanet class but not what is under the StarPanel class.

This is driving me crazy why I can get one to work and not the other.

Please help.

The content pane uses a BorderLayout by default. When you add a panel to the content pane, you add it to the center of the BorderLayout. So when you add the second panel, it replaces the first one in the center of the layout.

If you want the two panels to be painted one on top of the other, then you don't have the appropriate strategy. Create a single panel, which combines the paintings of the two panels you have at the moment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM