Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two icons in a JLabel?

Tags:

java

swing

jlabel

I have an icon in a JLabel as shown below:

enter image description here

Is it possible to add another icon (e.g. a flag representing a country) between the color icon and the text? For example, I want to add an icon depicting the U.S. flag between the red icon and US. Thanks!

like image 875
BJ Dela Cruz Avatar asked Oct 27 '11 19:10

BJ Dela Cruz


People also ask

How will you set icon for the JLabel?

To create a JLabel with an image icon we can either pass an ImageIcon as a second parameter to the JLabel constructor or use the JLabel. setIcon() method to set the icon.

What is difference between label and JLabel?

The fundamental difference between the two is that JLabel allows the label to be composed of text, graphics, or both, while the old Label class only allowed simple text labels. This is a powerful enhancement, making it very simple to add graphics to your user interface.

Can JLabel display images?

With the JLabel class, you can display unselectable text and images. If you need to create a component that displays a string, an image, or both, you can do so by using or extending JLabel .

How do you put a JLabel on top of a JLabel?

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);


1 Answers

Yes, use nested JLabel with BoxLayout in the container label:

JLabel container = new JLabel();
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
JLabel icon1Label = new JLabel();
JLabel icon2Label = new JLabel();
icon1Label.setIcon(icon1);
icon2Label.setIcon(icon2);
container.add(icon1Label);
container.add(icon2Label);
like image 53
Heisenbug Avatar answered Oct 02 '22 11:10

Heisenbug