javaswingjframejpanelborder-layout

Add JPanel inside of a BorderLayout?


I created a window with 5 panels and a BorderLayout but then had trouble drawing graphics.

I'm unsure of how to actually put that into a BorderLayout.CENTER because it doesn't seem to be the same way as before when I just made a new JPanel.

Could someone guide me on how to achieve this?

import javax.swing.*;
import java.awt.*;
      
public class GameScene2 {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                mainGameScene();
            }
        });
    }
         
    private static void mainGameScene() {
        JFrame window = new JFrame("This is my first game :o");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(new mainGamePanel());
        window.pack();
        window.setVisible(true);
    }
}
      
class mainGamePanel extends JPanel {

    public Dimension getPreferredSize() {
        return new Dimension(1280, 720);
    }
         
    public void paintComponent(Graphics pencil) {
        super.paintComponent(pencil);
        pencil.drawString("Boo", 100, 100);
    }
}

Solution

  • Panel p = new Panel();
    p.setLayout(new BorderLayout());
    

    add it to the frame like so.

    Here is a full link to explain how use use Borderlayout:

    https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html

    This explains how to add it to a panel:

    https://docs.oracle.com/javase/7/docs/api/java/awt/BorderLayout.html

    EDIT:

    So originally you have window.add(new mainGamePanel());

    instead try

    mainGamePanel p = new mainGamePanel();
    p.setLayout(new BorderLayout());
    window.add(p);