Reputation: 13
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();
}
}
Upvotes: 1
Views: 33
Reputation: 11143
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:
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.
Add your components as
frame.add(points, BorderLayout.NORTH); //Or choose the location from the link above
frame.add(panels, BorderLayout.CENTER);
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
And also don't forget to place your program on the EDT, see point #2 on this answer
Upvotes: 2