Hi I want to make a window, a GUI, and put an image in it.
I watched a YT tutorial (https://www.youtube.com/watch?v=Ap20Qw77TzY) and copied everything similar but the Window I make has no image at all. I tried different file types like .jpg and different window sizes, matching the picture size but it doesn't help.
That's my code, I get no real errors, except a warning of:
The serializable class main does not declare a static final serialVersionUID field of type long,line 8
This method has a constructor,line 25
Code
package main;
import java.awt.Graphics;
import java.awt.Toolkit;
import javax.swing.*;
public class main extends JFrame {
/**
* author jan
*/
public main(String title){
super (title);
}
public void paint(Graphics gr) {
super.paint(gr);
gr.drawImage(Toolkit.getDefaultToolkit().getImage("Koppenhagen\\Pictures\\Herz.png"), 0, 0, this);
}
public static void main(String[] args) {
main window = new main("Mein Test!");
window.setSize(160,160);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
ImageIO.read
overToolkit.getImage
, it will throw aIOException
of the image can't be load for some reasonKoppenhagen\\Pictures
, relative to the execution context of the program. You could useFile#exists
to check if the file actually exists where you think it ispaint
method, loading images can take time and painting should run as fast as possibleJFrame
. AJFrame
contains aJRootPane
, which contains, amongst other things, acontentPane
all of which can be painted independently of its parent container. Instead, start with aJPanel
and override itspaintComponent
method instead, then add this to an instance ofJFrame