I turns out Java has UI, and some even claim people use it. Here's my little app to play around with it a bit (I shortened it a little)
public class App {
public static void main(String[] args) {
MyUI ui = new MyUI();
ui.display();
}
}
public class MyUI {
public void display() {
new UIBuilder()
.withPanel(() -> new JPanel() {
@Override
protected void paintComponent(Graphics g) {
Image image = new ImageIcon("statics/img.png").getImage();
g.drawImage(image, 3, 4, this);
}
})
.visualize();
}
private static class UIBuilder {
private final JFrame frame;
{ // initialization and defaults
frame = new JFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private UIBuilder withPanel(Supplier<JPanel> panelSupplier) {
JPanel panel = panelSupplier.get();
frame.getContentPane().add(panel);
return this;
}
private UIBuilder withFrameSize(int width, int height) {
frame.setSize(width, height);
return this;
}
private UIBuilder withDefaultCloseOperation(int windowConstant) {
frame.setDefaultCloseOperation(windowConstant);
return this;
}
private void visualize() {
frame.setVisible(true);
}
}
}
The problem: no image is displayed. It's a 1200x800 PNG-file. In my attempt to troubleshoot, I changed the panel code to this
Image image = null;
try {
image = ImageIO.read(new File("statics/img.png"));
} catch (IOException e) {
e.printStackTrace();
}
if (image != null) {
g.drawImage(image, 3, 4, this); // I also tried g.drawImage(image, 3, 4, 200, 150, this);
} else {
System.out.println("Error loading image.");
}
Result:
javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1310)
at org.example.demos.ui.MyUI$1.paintComponent(MyUI.java:32)
What is causing the issue? The directory and the file name are ok
UPD: For some reason, specifying the path from the content root helped. If it's in the statics
folder, src/main/java/org/example/demos/ui/statics/img.png
does the job
new ImageIcon("src/main/java/org/example/demos/ui/statics/img.png").getImage()
I expected relative paths to be resolved relative to the main class directory. It was typically the case before, in other projects. I don't know why it's different here