Reputation: 1707
I initially created a JLabel
object and added it to JFrame
but the content was not showing up.I found a post on stackoverflow
using container to display JLabel
on JFrame
.I tried that too but even that didn't work.I went through a lot of posts but I couldn't find any solution.The button is being displayed but Jlabel is no where to be seen!
Dimension s=new Dimension(400,400);
JFrame l=new JFrame();
l.setSize(s);
l.setResizable(true);
Dimension s1=new Dimension(100,100);
Container me=new Container();
JLabel kingsman=new JLabel ("kingsman");
me.add(kingsman);
l.add(me);
JButton p=new JButton("Goal");
p.setSize(s1);
l.add(p);
//l.pack();
l.setVisible(true);
There is one more problem.When I call pack()
function,Jframe
is getting reduced to a small window instead of the dimension that I have mentioned.
Please Help!
Upvotes: 0
Views: 2616
Reputation: 451
The reason the label does not show up is that the content pane of a JFrame
uses a BorderLayout
as its LayoutManager
. When you call l.add(me)
and then l.add(p)
you are effectively replacing the Container
instance with the button. Try changing you Container
to a JPanel
, add both label and button components to that and then add it to your frame's content pane. Read up on Layout Managers, too.
The following example shows a JPanel
containing a JLabel
and JButton
arranged using the JPanel's
default LayoutManager
of FlowLayout
.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel content = new JPanel();
content.add(new JLabel("A Label"));
content.add(new JButton("A Button"));
frame.add(content);
frame.pack();
frame.setVisible(true);
Upvotes: 2