Reputation: 5
I got a problem, I was practicing on programming in Java a program that displays the java GUI with some text and an image The problem is that no images are displayed and I can't understand why Here's the code:
import java.awt.*;
import javax.swing.*;
public class DON extends JFrame {
private JPanel panel;
public DON() {
//Impostazioni finestra
JFrame finestra = new JFrame("Title of page");
finestra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
finestra.setLayout(null);
finestra.getContentPane().setBackground(Color.black);
finestra.setResizable(false);
finestra.setVisible(true);
finestra.setSize(1280, 720);
//Impostazioni pannello
JPanel pannello = new JPanel();
pannello.setBounds(450, 0, 200 , 30);
pannello.setBackground(Color.black);
JPanel startPanel = new JPanel();
startPanel.setBounds(0, 0, 1280 , 30);
startPanel.setBackground(Color.blue);
//Jpanel for images
JPanel imagePanel = new JPanel();
imagePanel.setBounds(0, 30, 1280, 720);
//Impostazioni label e ImageIcon
JLabel label = new JLabel("Image on JLabel!");
label.setBackground(Color.black);
label.setForeground(Color.white);
JLabel imageLabel = new JLabel( "test", new ImageIcon( "2.png" ), JLabel.LEFT );
/* put every jlabel to jpanel and put my jpanel to a container ; */
startPanel.add(imageLabel);
imagePanel.add(imageLabel);
pannello.add(imagePanel);
pannello.add(label);
Container con = finestra.getContentPane();
con.add(pannello);
con.add(imagePanel);
con.add(startPanel);
}
public static void main(String args[]) {
new DON();
}
}
Can you help me?
Upvotes: 0
Views: 71
Reputation: 2051
This is due to a problem with the location of your image file.
To fix it,I suggest this method.
new ImageIcon(this.getClass().getResource("2.png"))
Make sure to clean the build and then rebuild before running.
Or you can use the path starting from src folder
new ImageIcon("src/..../2.png") //put your correct path
EDIT:
You have to put finestra.setVisible(true);
at the last line of the constructor DON()
, otherwise you will get a black screen (as you already mentioned in the deleted answer)
Upvotes: 1