Search code examples
javaswinguser-interfaceintellij-ideapaintcomponent

Painting on one JPanel when two are in the frame


I have two JPanels inside my program's main JFrame for my GUI. One is a menu and the other should give display some graphics and then later animation. I'm trying to draw inside the latter panel.

Im using intelliJ's grid layout manager so that's made it a bit harder for me to find where to put what code.

Im new to Java so any help on how to paint on the AnimationPanel would be very greatly appreciated.

Here's my attempt so far -

Main Class:

public class ProjectileSim {

public static void main(String[] args){
    GUIForm1 gui = new GUIForm1();
    AnimationPanel animationPanel = new AnimationPanel();


}

}

AnimationPanel Class:

public class AnimationPanel extends JPanel {
@Override
public void paintComponent(Graphics g) {

    super.paintComponent(g);

    //axis
    g.setColor(Color.BLACK);
    g.fillRect(50, 0, 5, getHeight());
    g.fillRect(0, getHeight() - 50, getWidth(), 5);


    int axisY = 0;
    int axisX = 0;
    int axisYCounter = 1;
    int axisXCounter = 1;

    //axis markers
    while (axisYCounter <= getHeight() / 10) {
        g.fillRect(35, axisY, 20, 5);
        axisY = axisY + 50;
        axisYCounter++;
    }

    while (axisXCounter <= getWidth() / 10) {
        g.fillRect(axisX, getHeight() - 50, 5, 20);
        axisX = axisX + 50;
        axisXCounter++;
    }
}
}

GUIForm1 Class: (omitted a lot of this since it is mainly menu related)

public class GUIForm1 {


private JPanel MainPanel;
private JPanel MenuPanel;
private JPanel AnimationPanel;



public GUIForm1() {


    JFrame frame = new JFrame("Projectile Motion");
    frame.setContentPane(MainPanel);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setExtendedState(Frame.MAXIMIZED_BOTH);
    frame.pack();
    frame.setVisible(true);

Solution

  • You covered AnimationPanel with MainPanel. I commented this line:

    frame.setContentPane(MainPanel);

    and I was able to see your drawings.

    Remember to put AnimationPanel on frame by:

    frame.setContentPane(AnimationPanel);

    or other method (use layouts)