0

Whats the correct way to position a Jpanel in Jframe? I have tried to use BorderLayout.CENTER as a second arg in jframe.add(jpanel, BorderLayout.CENTER). I have also tried to setBounds(20, 20, width, height) in jpanel object and setAlignmentX((width+50)/2). But none of these worked, each of the above was ignored so the jpanel was positioned in the upper left corner, overlapping the window panel. I havent found a working solution on stackOverflow.

I want the gameboard positioned in a center of a jframe.

public class MainBoard extends JFrame {

    public MainBoard(String title,int width, int height){
        setTitle(title);
        setSize(new Dimension(width+50, height+50));
        setLocationRelativeTo(null);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        createBufferStrategy(2);
        GameBoard g = new GameBoard(width, height, getBufferStrategy());
        add(g);

    }

}
public class GameBoard extends JPanel implements Runnable {

    private final int WIDTH;
    private final int HEIGHT;
    private boolean inGame;
    private final BufferStrategy bs;
    private final int FRAME_DELAY = 50;
    private long cycleTime;

    public GameBoard(int width, int height, BufferStrategy bs) {
        addKeyListener(new TAdapter());
        setFocusable(true);
        setIgnoreRepaint(true);
        WIDTH = width;
        HEIGHT = height;
        this.bs = bs;
        gameInit();
    }

camickr
  • 321,443
  • 19
  • 166
  • 288
c4da
  • 73
  • 9
  • "Whats the correct way to position a Jpanel in Jframe?". There is no absolute correct way. there are different attempts, depending on what you want to achieve. A few of them, you have mentioned in your post. So what do you want to achieve, what you cant over a box layout? – chris576 Dec 31 '20 at 10:07
  • *What's the correct way to position a JPanel in a JFrame?* The correct way is to use [Swing layout managers](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html). Your question implies that you have multiple JPanels, but you only show one. Centering one JPanel is trivial. See this [Stack Overflow answer](https://stackoverflow.com/questions/65484190/java-on-eclipse-wont-show-the-jpanel-even-when-i-add-it-to-jframe/65485547#65485547) for the correct code to center one JPanel. – Gilbert Le Blanc Dec 31 '20 at 10:09
  • Ive edited the question. I want to position the GameBoard in a center of a jframe. Now the upper part of the GameBoard overlaps the window panel, any idea why? – c4da Dec 31 '20 at 10:48
  • 1
    Post your [mre] demonstrating the problem. – camickr Dec 31 '20 at 16:22

0 Answers0