Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

java - JLabel on top of another JLabel

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...