+1 to @AndrewThompsons comments.
1) Below is incorrect, you do not honer the paint chain by calling the supers implementation of super.paintComponent(...)
:
public void paintComponent(Graphics g) {
// Draw our Image object.
g.drawImage(image,50,10,574,960, this); // at location 50,10
// 200 wide and high
}
As per docs for paintComponent:
Further, if you do not invoker super's implementation you must honor
the opaque property, that is if this component is opaque, you must
completely fill in the background in a non-opaque color. If you do not
honor the opaque property you will likely see visual artifacts.
should be:
public class Ball extends JPanel {
BufferedImage image;
public Ball() {
super();
try {
image=ImageIO.read(new File("c:/test.jpg"));//change to your path of file
}catch(Exception ex) {//file did not load properly
ex.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
// Draw our Image object.
g.drawImage(image,0,0,image.getWidth(),image.getHeight(), this); // at location 50,10
// 200 wide and high
}
@Override
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(),image.getHeight());//replace with size of image
}
}
Also notice:
I overrode getPreferredSize()
of JPanel
and returned Dimension
s I wanted (i.e Image size) or the JPanel
will only be as big as the components added to it and not the image (so if no components 0,0).
I also chose BufferedImage
vs Image
and surrounded the statement with a try catch to check if any errors are thrown.
I see you also had g.drawImage(image,50,10...)
why 50 and 10 and not 0,0?
2) Also this (as @AndrewThompson has said):
image = Toolkit.getDefaultToolkit().getImage("/D:\\lolololo\\tuto\\bin\\sa.jpg");
No need for the / thats only if its located in your classes package etc not when its on your HDD at a set location.
3) also as said by @AndrewThompson a main method should be:
public static void main(String[] args){}
Notice the static modifer applied other wise its just another method.
4) Also dont use JFrame#setSize(..)
, rather use LayoutManager
and/or override getPreferredSize
and than simply call pack()
on JFrame
instance before setting it visible.
5) Also please have a read on Concurrency in Swing. especially the Event-Dispatch-Thread