1

I am adding both a JLabel and my own Panels class to a JFrame. The Panels class I made inherits from JPanel, by the way.

My code only shows one of the two components, the JLabel or the JPanel inherited class. When I add a setLayout() line, the JLabel shows and when I don't the JPanel inherited class shows. What's up with that?

public class TetisFrame extends JFrame{

    private final static int FRAME_WIDTH = 400;
    private final static int FRAME_HEIGHT = 720;

    private static Panels panels;

    public TetisFrame(){
        setTitle("Tetis");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(FRAME_WIDTH + 200, FRAME_HEIGHT + 50);
        setResizable(false);
        setLocationRelativeTo(null);

        JLabel points = new JLabel("Score: ");
        points.setBounds(450, 360, 100, 30);
        add(points);

        panels=new Panels();
        add(panels);
        addKeyListener(panels);

        setLayout(null);

        setVisible(true);
    }

    public static void main(String[] args) {
        new TetisFrame();
    }
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89
Josh
  • 13
  • 2
  • 1
    1) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Jun 06 '19 at 18:36
  • 1
    *"What's up with that?"* A `JFrame` has a `BorderLayout` by default. A border layout will only accommodate a single component in each layout constraint. – Andrew Thompson Jun 06 '19 at 18:41

1 Answers1

2

My code only shows one of the two components, the JLabel or the JPanel inherited class.

Because JFrame has a BorderLayout layout by default. And if you don't specify the location in BorderLayout, it will add the elements in the CENTER position.

So:

  1. I highly recommend don't extend JFrame and create an instance of it in your class better as you're not modifying its behavior anyway.

  2. Add your components as

    frame.add(points, BorderLayout.NORTH); //Or choose the location from the link above
    frame.add(panels, BorderLayout.CENTER);
    
  3. Don't use setLayout(null); as it will remove the Layout Manager and will produce some strange / funny / weird / crazy / annoying results like this one in different OS / Platform. Also don't manually set the bounds of your components, let the Layout Manager do it for you: points.setBounds(450, 360, 100, 30); don't use it. Null layout is evil and frowned upon

  4. And also don't forget to place your program on the EDT, see point #2 on this answer

Frakcool
  • 10,915
  • 9
  • 50
  • 89