How to position JPanel to upper right corner of JFrame

Android999 :

I have written a board game and have gotten to the point where I want to add a timer to the right corner of my JFrame. I was thinking it might be best solved through putting a JPanel in the upper right corner that I then will update with the count down time. However, I have run into the issue that I can't seem to figure out how to place the JPanel to a set location. Whatever I try to do it just seems to cover the entire screen, rather than the size and location I have put it to.


    private final JFrame frame = new JFrame("myBoardGame");
    private JPanel jp = new JPanel();

    public ShowBoard(Board board){
        frame.setResizable(false);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setContentPane(board);
        frame.setLayout(new BorderLayout());
        frame.pack();
        frame.setVisible(true);
        jp.setLayout(null);
        jp.setLocation(300,300);
        jp.setSize(100,100)
        frame.add(jp);
        this.board = board;
        getKeyBindings(); }

Instead of it moving to the location 300x300 and setting it size to 100x100 it makes the entire screen go grey. What am I doing wrong? I simply want to be able to move the JPanel around the JFrame to where it fits best.

Marco R. :

You can use a BorderLayout contentPane, as the frame's content pane. This pane would include:

  1. In its BorderLayout.NORTH position, a JPanel (timerPane) with a FlowLayout (with orientation ComponentOrientation.RIGHT_TO_LEFT). You can use this panel to house your timer Component.
  2. In its BorderLayout.CENTER position, your board.

Your code (modified to include this considerations) would look like this:

private final JFrame frame = new JFrame("myBoardGame");
private JPanel contentPane = new JPanel(new BorderLayout());
private JPanel timerPane = new JPanel(new FlowLayout());

public ShowBoard(Board board){
    timerPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    contentPane.add(timerPane, BorderLayout.NORTH);
    contentPane.add(board, BorderLayout.CENTER);

    frame.setResizable(false);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setContentPane(contentPane);
    frame.pack();
    frame.setVisible(true);

    this.board = board;
    getKeyBindings(); 
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=149422&siteId=1