|
-
July 4th, 2025, 02:35 AM
#1
Swing - How to set an image filename
I made a Java program with Swing libraries that displays text and an image.
Both the text string and the image filename are set via a set method, but while the text is displayed correctly, the image is not.
If I set the filename directly in the constructor then it works, but it is not what I want to do.
I cannot find a way to pass the filename to display the image.
The intention is to periodically pass an array of strings and a set of image filenames, to have a GUI with text and image changing over time.
Here is the code simplified:
Code:
import javax.swing.*;
import java.net.URL;
class Swing extends JFrame {
private JLabel label = new JLabel();
private String imageFilename = new String();
Swing()
{
super("Swing Test Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000, 700);
setLayout(null);
setLocationRelativeTo(null);
label.setBounds(10, 0, 220, 100);
add(label);
//String imageFilename = "images\\image-1.jpg";
URL imageURL = getClass().getResource(imageFilename);
if (imageURL != null) {
ImageIcon imageIcon = new ImageIcon(imageURL);
JLabel imageLabel = new JLabel(imageIcon);
imageLabel.setBounds(10, 200, 420, 420);
add(imageLabel); // Aggiungi l'etichetta al frame
} else {
System.err.println("Image " + imageFilename + " not found.");
}
setVisible(true);
}
void SetText(String strLabel, String imageFilename)
{
label.setText(strLabel);
this.imageFilename = imageFilename;
return;
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|