I've been working on some simple Java code with the intention of making images appear on-screen. I've figured it out, but strangely, the code only works on the second+ attempt of running it. The code is as follows:
import javax.swing.*;
public class A3011A {
public static JFrame frame;
public static int delay;
public static void main(String[] args) {
CreateWindow(800, 600, "Frame");
ImageIcon img = new ImageIcon("H:/Intro to Programming/Semester Project/duck.png");
AddImage(50, 0, img);
AddLabel(0, 0, "top left");
AddLabel(300, 300, "another label");
}
public static void CreateWindow(int x, int y, String name) {
frame = new JFrame(name);
frame.setSize(x, y);
frame.setLayout(null);
frame.setVisible(true);
}
public static void AddLabel(int x, int y, String text) {
JLabel label = new JLabel(text);
label.setSize(300, 13);
label.setLocation(x, y);
frame.add(label);
}
public static void AddImage(int x, int y, ImageIcon image) {
JLabel label = new JLabel(image);
label.setSize(image.getIconWidth(), image.getIconHeight());
label.setLocation(x, y);
frame.add(label);
}
}
It is worth noting that the following line:
ImageIcon img = new ImageIcon("H:/Intro to Programming/Semester Project/duck.png");
seems to be a source of the problem. If this line is removed, the program works on the first run attempt. Is there anything obvious sticking out here?
There are no compiler errors/exceptions when the program is run. The only thing wrong is the window; nothing appears in it on the first run. On the second run or after, everything appears in the window.