Question

Is it possible to add a JLabel on top of another JLabel? Thanks.

Was it helpful?

Solution

The short answer is yes, as a JLabel is a Container, so it can accept a Component (a JLabel is a subclass of Component) to add into the JLabel by using the add method:

JLabel outsideLabel = new JLabel("Hello");
JLabel insideLabel = new JLabel("World");
outsideLabel.add(insideLabel);

In the above code, the insideLabel is added to the outsideLabel.

However, visually, a label with the text "Hello" shows up, so one cannot really see the label that is contained within the label.

So, the question comes down what one really wants to accomplish by adding a label on top of another label.


Edit:

From the comments:

well, what i wanted to do was first, read a certain fraction from a file, then display that fraction in a jlabel. what i thought of was to divide the fraction into 3 parts, then use a label for each of the three. then second, i want to be able to drag the fraction, so i thought i could use another jlabel, and place the 3'mini jlabels' over the big jlabel. i don't know if this will work though..:|

It sounds like one should look into how to use layout managers in Java.

A good place to start would be Using Layout Managers and A Visual Guide to Layout Managers, both from The Java Tutorials.

It sounds like a GridLayout could be one option to accomplish the task.

JPanel p = new JPanel(new GridLayout(0, 1));
p.add(new JLabel("One"));
p.add(new JLabel("Two"));
p.add(new JLabel("Three"));

In the above example, the JPanel is made to use a GridLayout as the layout manager, and is told to make a row of JLabels.

OTHER TIPS

The answer to your original question is yes for the reasons given that any Component can be added to a Container.

The reason you don't see the second label is because by default a JLabel uses a null layout manager and the size of the second label is (0, 0) so there is nothing to paint. So all you need to do is set the bounds of the second label and away you go.

You can't use a layout manager if you want to drag components around because as soon as you resize the frame etc, the layout manager will be invoked and the components will be repositioned based on the layout manager of the component.

it's a matter of layout. you can do that using null layout (with hard coded locations) or with a custom layout.

you can use a JLayeredPane and set it's border to No Border.

you can add put them above each others by using the horizontal or vertical gap (hgap,vgap) the attributes of the layout
JPanel p = new JPanel(new GridLayout(2, 1,-40,0)); //the 40 is the hgap , make it the same with the label height .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top