简体   繁体   中英

JLabel with Image?

Honestly, I am not that familiar with GUI and I'm still having a study about it. My question is, how can I combine an image and a label? I want to have an output that there's a text above the picture. Here's the code I got from a reference

import java.awt.Container; 
import java.awt.EventQueue; 

import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 

class JavaApplication2 extends JFrame { 


public JavaApplication2(String title, String imageFileName) { 
setTitle("title"); 
ImageIcon icon = new ImageIcon(imageFileName); 
Container pane = getContentPane(); 
JLabel label = new JLabel(icon); 
pane.add(label);
} 


public static void main(String[] args) { 

EventQueue.invokeLater(new Runnable() { 
public void run() { 

JFrame f = new JavaApplication2("Orca","C:/Users/Balmaceda/Desktop/Naomi       
/Capture.png"); //change pic here
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack(); 
f.setVisible(true); 

} 
}); 

} 
}

and this thing here:

JLabel label = new JLabel(icon);

everytine I change the (icon) into ("icon"), only the word icon is displayed on the window. The picture is no longer there.

What I want to happen is the word icon is above the picture.

Start by taking a look at How to Use Labels and The JavaDocs for `javax.swing.JLabel

Basically, you have a number of options.

You can use

JLabel label = new JLabel("This is an Icon", icon, JLabel.CENTER);

You can use

JLabel label = new JLabel();
label.setText("This is an icon");
label.setIcon(icon);

You can use

JLabel label = new JLabel("This is an icon");
label.setIcon(icon);

You can use

JLabel label = new JLabel(icon);
label.setText("This is an icon");

To centre the text over the image you could use something like...

label.setVerticalTextPosition(JLabel.TOP);
label.setHorizontalTextPosition(JLabel.CENTER);

You will want to check the JLabel API for there you'll find the correct constructor, one with an Icon, a String and an int for horizontal alignment:

public JLabel(String text,
          Icon icon,
          int horizontalAlignment)

horizontalAlignment - One of the following constants defined in SwingConstants: LEFT, CENTER, RIGHT, LEADING or TRAILING.

Another way to show images in JLabel, is to use HTML:

String imageInHtml = "<html> Image 1 </br> <img src = \"/absolute/path/to/file.jpg\" height = \"120\"  width =\"50\"/> </html>";
JLabel l = new JLabel(imageInHtml);

this way you an also show easily multiple images with one label.

PS:
This also works with images which are in a jar on the classpath.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM