I've been struggling with this problem for weeks to no avail. Other Java forums have not been able to help me with this so I'm hoping I can find someone here with new eyes. I have a JFrame
in which, among other things, I am trying to insert an image. I have put together an SSCCE that reproduces the problem.
public class ImageTest {
public static void main(String[] args) {
SplashScreen.ShowWindow();
}
}
public class SplashScreen {
private JFrame frmKcbsEventsSearch;
public SplashScreen() {
initialize();
}
public static void ShowWindow() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SplashScreen window = new SplashScreen();
window.frmKcbsEventsSearch.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void initialize() {
frmKcbsEventsSearch=new JFrame();
frmKcbsEventsSearch.getContentPane().setBounds(new Rectangle(200, 200, 520, 450));
frmKcbsEventsSearch.getContentPane().setFont(new Font("Times New Roman", Font.PLAIN, 16));
frmKcbsEventsSearch.setTitle("KCBS Events Search");
frmKcbsEventsSearch.setBounds(200,200,520,450);
frmKcbsEventsSearch.getContentPane().setLayout(new FlowLayout());
frmKcbsEventsSearch.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JLabel logo;
java.net.URL logoURL=getClass().getResource("KCBSLogo.jpg");
if (logoURL!=null) {
try {
logo = new JLabel();
logo.setIcon(new ImageIcon(logoURL));
}
catch (Exception e) {
logo = new JLabel("KCBS Logo");
}
}
else {
logo = new JLabel("KCBS Logo missing");
}
logo.setHorizontalAlignment(SwingConstants.CENTER);
logo.setVerticalAlignment(SwingConstants.CENTER);
frmKcbsEventsSearch.getContentPane().add(logo);
}
}
It has been mentioned elsewhere that the layout is important to make this work. I've not had much luck getting layout managers to do what I want but in this case I just want to get the image displayed. Once I have that I'll work through getting it formatted the way I want.
This code works perfectly fine! I changed the KCBSLogo.jpg to a source that I had named tile.png. When I ran it displayed perfectly. Make sure the KCBSLogo.jpg is in your SRC folder in the project.
https://i.stack.imgur.com/sYfYF.png
As you can see the tile image was shown.