0

I have been trying to upload an image onto a Java Applet Window but unfortunately it turns out to be blank..Here is the code i have written pls help!

import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.net.*;
import java.util.*;

public class RandomImages extends JFrame
{
  private Image img;

public void static main(String[] args)
{
  new RandomImages();
}

public RandomImages()
{
  super("Random Images");
  setSize(450,450);
  setVisible(true);
  setResizable(false);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  Toolkit tk=Toolkit.getDefaultToolkit();
  img=tk.getImage(getURL("Your File Name"));
}

Below is the code that fetches the url of the filename looking for...

private URL getURL(String filename)
{
  URL url=null;
  try{
    url=this.getClass().getResource(filename);
  }
  catch(Exception e) {}
  return url;
}

AffineTransform id=new AffineTransform();    

Code for paint component...

public void paint(Graphics g)
{
  super.paint(g);
  Graphics2D g2d=(Graphics2D)g;
  AffineTransform trans=new AffineTransform();
  Random rand=new Random();
  g2d.setColor(Color.BLACK);
  width=getSize().width;
  height=getSize().height;
  g2d.fillRect(0,0,width,height);

Loop for generating random ships on screen

for(int s=0;s<20;s++)
{
  trans.setTransform(id);
  trans.translate(rand.nextInt()%width,rand.nextInt()%height);
  trans.rotate(Math.toRadians(360*rand.nextDouble()));
  double scaled=rand.nextDouble()+1;
  trans.scale(scaled,scaled);
  trans.drawImage(img,trans,this);
}
}

}
Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
  • 1
    1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) One way to get image(s) for an example is to hot-link to the images seen in [this answer](http://stackoverflow.com/a/19209651/418556). – Andrew Thompson Nov 28 '13 at 06:06

2 Answers2

0

The best way to add image in JFrame is to use JLabel.

Example:

 JLabel image = new JLabel(new ImageIcon("Image.jpg"));

Now add this JLabel(image) into your JFrame.

public RandomImages()
{
  super("Random Images");
  setSize(450,450);
  setVisible(true);
  setLayout(new FlowLayout());//you have not used the Layout
  setResizable(false);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  JLabel image = new JLabel(new ImageIcon("Image.jpg"));
  add(image);
}

Another way is to use drawImage() function of Graphics class in paint(Graphics g) function . But you should use paintComponent against paint

AJ.
  • 4,526
  • 5
  • 29
  • 41
0

1)Instead of using paint(Graphics g) for custom paintings you need to use paintComponent(Graphics arg0) of JComponent. For example draw image on JPanel and the add panel to your frame. Your JFrame isn't a JComponent.

2) As I know public static void main(String[] args) ;)

Read more about customPaintings.

alex2410
  • 10,904
  • 3
  • 25
  • 41