JApplet image

Does anyone know how to place an image in an application using JApplet? Please hep if you do know i need a picture to show up in an application and not an applet

you can use this...
Toolkit tk = Toolkit.getDefaultToolkit();
Image img = tk.getImage("img.jpg");
public void paint(Graphics g){
     // this will draw the image...
     g.drawImage(img, col, row, this);
}or you can use JLabel...
ImageIcon icons = new ImageIcon("img.jpg");
// some code here...
getContentPane(new JLabel(icons)));

Similar Messages

  • JApplet Image Buttons not init().

    I have created a JApplet where it contains image buttons. When I run the applet in a web page I get an error message, not inialised.
    I have been informed that the reason is the image buttons. Does the getCodeBase() method form part of the solution and if so does anyone know how.
    I have been going mad trying to find a solution.
    Thanks

    I have created a JApplet where it contains image buttons. When I run the applet in a web page I get an error message, not inialised.
    I have been informed that the reason is the image buttons. Does the getCodeBase() method form part of the solution and if so does anyone know how.
    I have been going mad trying to find a solution.
    Thanks

  • Can display image from PixGrabber

    hi
    i try to grab pixels from an image to an array , biuld it as a new image object and draw it to the screen . i test that the array get the values and it does , and i dont recieve any exception. it just problem with displaing the image
    here is the code:
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.*;
    // the pic is 47 x 51 / gif
    public class grabbing extends JApplet{
      Image img,gen;
      int[] pixels;
      void grabData(Image img,int h,int w,int x, int y){
        int[] pixels = new int[w * h];
         PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
          try {
             pg.grabPixels();
          } catch (InterruptedException e) {
             System.err.println("interrupted waiting for pixels!");
             return;
          if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
             System.err.println("image fetch aborted or errored");
             return;
          // for(int t=0;t<pixels.length;t++)
          //System.out.println("xx "+ pixels[t]);
        public  void init(){
         img = getImage(getCodeBase(),"pic.gif");
         grabData(img,40,40,20,20);
        public void paint(Graphics g){
          gen = createImage(new MemoryImageSource(51, 47, pixels, 0, 51));
          g.drawString("ssssss",25,25);
          g.drawImage(gen,100,100,this);
      }thanks in advance
    Shay

    sorry about the title
    can not display from PIxGrabber (wish i could:)

  • Help! Image OverLapping components. Get Your dukes right here.

    I am creating an applet and I want to use an image as a background to a jPanel. There is a jTextField on the panel that is hidden because the BG image overlaps it. I would like the image to be used as a background and only as a background. Any Suggestions? Duke Dollars will be awarded.
    public class Tester extends JApplet
      Image imageTest;
      Graphics dbg;
      Image dbImage;
      JScrollPane jScrollPane1 = new JScrollPane();
      public Tester()
      public void init()
        try
          jbInit();
          imageTest = getImage( getDocumentBase(), "bg.gif");
        catch(Exception e)
          e.printStackTrace();
      private void jbInit() throws Exception
        this.getContentPane().setLayout(null);
        jScrollPane1.setBounds(new Rectangle(70, 30, 235, 215));
        jScrollPane1.setBackground(Color.black);
        jScrollPane1.setForeground(Color.white);
        this.getContentPane().add(jScrollPane1, null);
      static 
        try
          // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          // UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        catch(Exception e)
    public void paint(Graphics g)
        g.drawImage(imageTest, 0,0, this);
    }

    Check out this thread:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=316074

  • Buttons are not displayed for the first time when drawImage method is used

    Hi
    In my swing window 2 buttons are there and when clicking these buttons, it should display an image . The two buttons are displayed at the first time and I can click on it . While clicking a button , the corresponding image is also got displayed. [ I am using drawImage() function for it] But what the problem is, then the two buttons are not displayed and it will be displayed again when the mouse moves along the position of these two buttons. And this problem occurs only at the first time..When they are on the window on a second time, they won't vanish when the image is displayed when clicking it. Is this the problem with paint() method?. I am using start() method also.
    Please help me!
    Thank You

    Hi
    This is not my exact program, that has a large no: of code. So I am putting here a sample one. One thing I would like to point out is that , I can see the buttons at the time of loading the applet and suddenly it vanishes and the image is drawn. Then if I move the mouse along the position of these buttons , they got displayed.
    import java.awt.*;
    import javax.swing.*;
    /*<applet code = MyClass width = 500 height = 500>
    </applet>
    public class MyClass extends JApplet
    Image img;
    JButton b1,b2;
    Container cp;
    Canvas1 cv;
    class Canvas1 extends JPanel
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(Color.black);
    g.fillRect(0,0,500,500);
    img = getImage(getCodeBase(),"image1.jpeg");
    g.drawImage(img,20,20,this);
    public void start()
    cv = new Canvas1();
    cv.setBounds(0,0,500,500);
    cp.add(cv);
    public void init()
    setLayout(null);
    cp = getContentPane();
    b1 = new JButton("Button1");
    b1.setBounds(1,1,100,30);
    cp.add(b1);
    b2 = new JButton("Button2");
    b2.setBounds(200,1,100,30);
    cp.add(b2);
    It would be very helpful to me if you could fix the problem.
    Thank You.

  • Painting jpeg in java application: non-static method ... static context

    Hi!
    I simply want to show a jpeg within a java application. Showing the jpeg in an applet is no problem (see code below). But I have difficulties to translate this code to a java application. No matter what I try to load the jpeg, I end up with the following error:
    non-static method createImage() cannot be referenced from a static context
    How can I surround it? Thanx in advance for your help!
    Working applet
    import java.applet.*;
    import java.awt.*;
    public class shJpAp extends javax.swing.JApplet {
    Image pic;
    /** Creates a new instance of shJpAp */
    public shJpAp() {
    public void init() {
    pic=getImage(getCodeBase(), "lemmer.jpg");
    prepareImage(pic,this);
    public void paint (Graphics g) {
    g.drawImage(pic,0,0,this);
    Application
    import java.awt.*;
    public class shJp extends javax.swing.JFrame {
    Image pic;
    /** Creates new form shJp */
    public shJp() {
    initComponents();
    //pic = java.awt.Toolkit.getImage("lemmer.jpg");
    ---> pic = java.awt.Toolkit.createImage("lemmer.jpg");
    ---> prepareImage(pic, this);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent evt) {
    exitForm(evt);
    pack();
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
    System.exit(0);
    * @param args the command line arguments
    public static void main(String args[]) {
    new shJp().show();
    // Variables declaration - do not modify
    // End of variables declaration
    public void paint( Graphics g) {
    g.drawImage(pic, 0,0,this);
    }

    Hi,
    just want to add a solution I found in some textbook (see code below). I hate finding every possible question in the internet, but seldom fitting answers.....
    But again, one little thing pushed me close to my first heart attack: The code below works well when executed by foot (...java showPic...). In the NetBeans 3.6 the frame refuses to show the pic!
    I am looking for an appropiate forum - but if anyone of you can help, it would be very nice ;-)
    import java.awt.*;
    import java.awt.event.*;
    public class showPic extends Frame {
    Image pic;
    public showPic() {
    addWindowListener( new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    pic = getToolkit().getImage("lemmer.jpg");
    setSize(200,100);
    setVisible(true);
    public void paint(Graphics g) {
    if (pic != null) {
    g.drawImage(pic,60,20,this);
    public static void main( String[] args ) {
    new showPic();
    }

  • Please! Help Applets and IE 5.5!

    To see more about my question and a code example, go to my last post: http://forum.java.sun.com/thread.jsp?forum=31&thread=198915
    I am fairly new to Java, so try not to reply to me like you would reply to a seasoned Java programmer. My question may have been answered in my last post, but if it was, I didn't get it. I don't think it was answered, though.
    Every applet that I program runs correctly in appletviewer. I write my applets correctly and compile them correctly. I write my .html files correctly, also. But whenever I try to view my applets through my IE 5.5 browser and Windows ME, they will not run. It either says that the class cannot be found or that it is not initialized. The class is in the same folder as the .html file. What confuses me more is that I can view applets from websites accross the net. What is wrong?!
    Thanks.

    This works fine , Change back the name of the Image.
    import java.awt.*;
    import javax.swing.*;
    import java.applet.Applet;
    import java.net.*;
    public class bib extends JApplet
       Image        mainImage;
       ImageIcon    mainIconImage;
    //Load the image when the applet is loaded
    public void init()
         mainImage     = getImage(getDocumentBase(), "map.gif");
         try
              mainIconImage = new ImageIcon(new URL(getDocumentBase()+"map.gif"));
         catch(MalformedURLException e)
    //Display the image
    public void paint(Graphics g)  
    //draw the orginal image
         g.drawImage(mainImage, 0, 0, this); 
    //draw the image scaled to fit the width of the applet  
    //and the height of the applet minus 50 pixels 
         g.drawImage(mainImage, 0, 50, getWidth(), getHeight() - 50, this);
    //draw the icon using its paintIcon method  
         mainIconImage.paintIcon(this, g, 300, 300); 
    Noah

  • Help Please - Buttons are not displayed in some platforms/browsers

    I've designed my website using flash 8 and I've just noticed
    that the buttons aren't being displayed on all browser/platforms.
    It works fine on the majority of them but I just went to a couple
    of places and accessed my page and the buttons are not shown at
    all. Anyone knows why it works in some platforms and not in others?
    What can I do to fix this problem?
    my website is:
    http://www.threecellos.co.uk
    Marcello

    Hi
    This is not my exact program, that has a large no: of code. So I am putting here a sample one. One thing I would like to point out is that , I can see the buttons at the time of loading the applet and suddenly it vanishes and the image is drawn. Then if I move the mouse along the position of these buttons , they got displayed.
    import java.awt.*;
    import javax.swing.*;
    /*<applet code = MyClass width = 500 height = 500>
    </applet>
    public class MyClass extends JApplet
    Image img;
    JButton b1,b2;
    Container cp;
    Canvas1 cv;
    class Canvas1 extends JPanel
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(Color.black);
    g.fillRect(0,0,500,500);
    img = getImage(getCodeBase(),"image1.jpeg");
    g.drawImage(img,20,20,this);
    public void start()
    cv = new Canvas1();
    cv.setBounds(0,0,500,500);
    cp.add(cv);
    public void init()
    setLayout(null);
    cp = getContentPane();
    b1 = new JButton("Button1");
    b1.setBounds(1,1,100,30);
    cp.add(b1);
    b2 = new JButton("Button2");
    b2.setBounds(200,1,100,30);
    cp.add(b2);
    It would be very helpful to me if you could fix the problem.
    Thank You.

  • IconImage - Putting Icons on Labels

    Please can anyone help...
    I have been trying to insert an icon onto a JLabel.
    The process works just fine if I view the result in the appletviewer.
    But in the web browsers it raises a security issue and the whole applet refuses to load. The following message apppears: "Exception:java.security.AccessControlException:
    access denied(java.io.FilePermission scribe32.gif read)"
    I have tried reducing all security in the browsers (iex6.xx and Netscape7.1) down to zero. But to no avail..
    Here is a snippet of relevent code:...
    void makeNorthPanel() {
         NorthPanel = new JPanel();
         ImageIcon ii = createImageIcon("scribe32.gif");
         JLabel jl = new JLabel("", ii, JLabel.CENTER);     
         SpacerN = new JLabel(" Fuzzy Log Java", JLabel.LEFT);
         FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
              NorthPanel.setLayout(flow);
              SpacerN.setFont(font);     
              NorthPanel.add(jl);          
              NorthPanel.add(SpacerN);
              NorthPanel.setBackground(Color.lightGray);
    Examples from Java2 manuals also won't run in the browsers...but will in the appletviewer so the code does not seem to be the problem...
    I would be very greatful for any assistance.. thanks Bill

    public class JLabelDemo extends JApplet {
         Image img;
         public void init() {
         img = getImage(getDocumentBase(), getParameter("img"));
         Container contentPane = getContentPane();          
         ImageIcon ii = new ImageIcon(img);
         JLabel jl = new JLabel("zzzz", ii, JLabel.CENTER);
         contentPane.add(jl);
    Using getImage with a <param name="img" value="xxx.gif"> declaration in the html file solves the problem. Thank you for all the help...

  • Trying to paint a gif

    This is my code for an applet to paint a gif file. All that happens when i run the code is that the applet is white, (nothing is being painted). What is wrong with my code?
    import java.awt.*;
    import java.applet.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.image.*;
    public class Test extends JApplet
         Image stuff;
         public void init()
              stuff= getImage(getDocumentBase( ), "h:/Java/Black_Jack/stuff.bmp");
         public void paint(Graphics g)
              g.drawImage(stuff, 12, 50, this);
    }

    Put the following code in a class file and get it to work:
        public static void main(String[] d) throws Exception {
            String source = "your image's path here";
            java.awt.Image image = javax.imageio.ImageIO.read(new File(source));
            javax.swing.JLabel lab = new javax.swing.JLabel(new javax.swing.ImageIcon(image));
            javax.swing.JOptionPane.showMessageDialog(null, lab, null, javax.swing.JOptionPane.PLAIN_MESSAGE);
            System.exit(0);
        }   Change the source string accordingly. Try with different images. If it works with the image the path of which you posted first, then either you haven't explored the "document base" issue enough, or ... we'll see.

  • Please enhance my code so that it can rotate text at the given angle

    public class ShapeDrawD extends JApplet
    Image img,imgback;
    static Image someimg2;
    ShapeCanvas canvas;
    ShapeCanvas backcanvas;
    public static int txtimgflag = -1,size,angle;
    public static String stringToDraw = "";
    public static int fontSize;
    public static String fontName;
    public static String fontStyle;
    public static String imgName;
    public static ImageObserver io;
    public static Shape shapeBeingDraggedtemp = null;
    public static Shape shapeBeingEdited = null;
    static Font fontmain;
    static Color colormain;
    static Color frocolor;
    public static String color;
    static Shape s = null;
    static JLabel l1 = new JLabel("");
    static String msg="";
    static JSObject js;
    public static URL url;
    public static URLConnection conn;
    public static String hostname;
    public static int port;
    static int addnew = 0;
    public static String str1;
    public static int str2;
    public static int zx, zy, oldy, zwidth,zheight;
    public static float scalingfactor;
    //Method which is called from Java Script taking parameters related to string and used for drawing strings
    public void printSomething(String str,String lname,String lstyle,String lsize,String lcolor,String lmsg,String frcol,String ang)
    try
    addnew = 1;
    colormain= new Color((Integer.decode("0X".concat(lcolor))).intValue());
    frocolor= new Color((Integer.decode("0X".concat(frcol))).intValue());
    fontmain = new Font(lname,Integer.parseInt(lstyle),Integer.parseInt(lsize));
    stringToDraw = str;
    size=Integer.parseInt(lsize);
    angle=Integer.parseInt(ang);
    msg=lmsg;
    str1=lname;
    str2=Integer.parseInt(lstyle);
    txtimgflag=0;
    drawIt();
    repaint();
    catch(NumberFormatException nfe)
    System.out.println("Please Enter Proper Numeric values");
    public void strdelete()
    if(canvas.isVisible() && shapeBeingEdited != null)
    //System.out.println("3inggggggggg "+ ((StringShape)shapeBeingEdited).Mystring);
    canvas.deleteit(shapeBeingEdited);
    addnew = 0;
    drawIt();
    repaint();
    else if(backcanvas.isVisible() && shapeBeingEdited != null)
    //System.out.println("Deletinggggggggg "+ ((StringShape)shapeBeingEdited).Mystring);
    backcanvas.deleteit(shapeBeingEdited);
    addnew = 0;
    drawIt();
    repaint();
    //Method which is called from Java Script taking parameters related to Editing string and used for drawing Edited strings
    public void editText(String str,String lname,String lstyle,String lsize,String lcolor,String lmsg,String frcol,String ang)
    addnew=0;
    //System.out.println("addnew "+ addnew);
    colormain= new Color((Integer.decode("0X".concat(lcolor))).intValue());
    frocolor= new Color((Integer.decode("0X".concat(frcol))).intValue());
    fontmain = new Font(lname,Integer.parseInt(lstyle),Integer.parseInt(lsize));
    stringToDraw = str;
    size=Integer.parseInt(lsize);
    msg=lmsg;
    angle=Integer.parseInt(ang);
    txtimgflag = 0;
    if(shapeBeingEdited != null && shapeBeingEdited instanceof StringShape)
    ((StringShape)shapeBeingEdited).Mystring=stringToDraw;
    ((StringShape)shapeBeingEdited).Mycolor=colormain;
    ((StringShape)shapeBeingEdited).Myfont=fontmain;
    ((StringShape)shapeBeingEdited).msg=msg;
    ((StringShape)shapeBeingEdited).frcolor=frocolor;
    ((StringShape)shapeBeingEdited).Siz=new Integer(size);
    ((StringShape)shapeBeingEdited).ang=new Integer(angle);
    drawIt();
    repaint();
    //Method Called from JavaScript used To Draw an Image takes Image name as param
    public void setImgName(String limgName)
    txtimgflag = 1;
    addnew = 1;
    imgName = limgName;
    someimg2 = getImage(getDocumentBase(),imgName);
    //System.out.println("Path -- >"+getDocumentBase() + imgName);
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(someimg2,1);
    try
    mt.waitForAll();
    catch(Exception e)
    e.printStackTrace();
    drawIt();
    repaint();
    public void setImageWidthHeight(String lparamwidth,String lparamHeight)
    int width = Integer.parseInt(lparamwidth);
    int height = Integer.parseInt(lparamHeight);
    if(shapeBeingEdited != null && shapeBeingEdited instanceof ImageShape)
    addnew=0;
    ((ImageShape)shapeBeingEdited).htwtimg(width,height);
    drawIt();
    repaint();
    /*Method to save Image on the Server .
    this methos makes a call to servlet and passes ImageIcon to it which is then saved
    as a jpeg file on given path
    public void uploadImage(BufferedImage fimg,BufferedImage bimg)
    try
    String path = "http://"+hostname+":"+port+"/javatool/sampleServlet";
    url = new URL(path);
    //System.out.println("after url");
    //System.out.println("Path--->"+path);
    conn = url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Content-type", "application/x-java-serialized-object");
    BufferedImage bi = fimg;
    Image imgg=(Image)bi;
    ImageIcon imgc = new ImageIcon(imgg);
    ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
    out.writeObject(imgc);
    bi = null;
    imgg= null;
    imgc= null;
    out.flush();
    bi = bimg;
    imgg=(Image)bi;
    imgc = new ImageIcon(imgg);
    out.writeObject(imgc);
    out.flush();
    out.close();
    //System.out.println("file saved...");
    InputStream ins = conn.getInputStream();
    ObjectInputStream objin = new ObjectInputStream(ins);
    String msg = (String)objin.readObject();
    //System.out.println(msg.toString());
    catch (java.io.IOException io)
    //System.out.println("IOException ----->" + io);
    catch (Exception e)
    //System.out.psrintln("Exception " + e);
    }//End of Upload
    //Applet Init()
    public void init()
    js = JSObject.getWindow(this);
    hostname = getCodeBase().getHost();
    port = getCodeBase().getPort();
    //System.out.println("HostName -->" + hostname );
    //System.out.println("port -->" + port);
    JButton buttcolor = new JButton("Choose Color");
    JButton front = new JButton("Front");
    JButton back = new JButton("Back");
    /*JButton save = new JButton("Save");*/
    img = getImage(getDocumentBase(),getParameter("img"));
    //System.out.println(getDocumentBase() +" \\ "+getParameter("img"));
    canvas = new ShapeCanvas(img);
    imgback = getImage(getDocumentBase(),getParameter("imgback"));
    backcanvas = new ShapeCanvas(imgback);
    scalingfactor = (float) 1.0;
    // txtimgflag = 2;
    getContentPane().setLayout(null);
    getContentPane().setSize(325,300);
    io = (ImageObserver)this;
    addMouseListener(canvas);
    addMouseListener(backcanvas);
    JPanel top = new JPanel();
    JPanel bottom = new JPanel();
    top.add(front);
    top.add(back);
    top.setSize(425,50);
    top.setLocation(0,0);
    final JColorChooser colorchooser = new JColorChooser();
    final JFrame internalfrm = new JFrame("Please Choose the Colors");
    internalfrm.setSize(450,320);
    internalfrm.setVisible(false);
    internalfrm.getContentPane().add(colorchooser);
    canvas.setSize(425,370);
    canvas.setLocation(0,50);
    backcanvas.setSize(425,370);
    backcanvas.setLocation(0,50);
    backcanvas.setVisible(false);
    bottom.setLayout(null);
    buttcolor.setLocation(175,10);
    buttcolor.setSize(120,30);
    /*save.setLocation(220,10);
    save.setSize(120,30);*/
    l1.setLocation(10,45);
    l1.setSize(300,30);
    bottom.add(l1);
    bottom.add(buttcolor);
    /*bottom.add(save);*/
    bottom.setSize(425,100);
    bottom.setLocation(0,420);
    bottom.setBackground(Color.lightGray);
    getContentPane().add(top);
    getContentPane().add(bottom);
    getContentPane().add(backcanvas);
    getContentPane().add(canvas);
    //sets Background of two panels i.e front and back
    colorchooser.getSelectionModel().addChangeListener(new ChangeListener()
    public void stateChanged(ChangeEvent e)
    canvas.setBackground(colorchooser.getColor());
    backcanvas.setBackground(colorchooser.getColor());
    //Shows Color Chooser
    buttcolor.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    internalfrm.setVisible(true);
    //Show back panel and hide front
    back.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    canvas.setVisible(false);
    backcanvas.setVisible(true);
    //backcanvas.repaint();
    //Show front panel and hide back
    front.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    backcanvas.setVisible(false);
    canvas.setVisible(true);
    *Save Image a call to UploadIamge
    save.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    uploadImage(canvas.bimg,backcanvas.bimg);
    drawIt();
    repaint();
    } //End of Applet Init();
    //Generates a Action Event calling ActionPerformed
    public void drawIt()
    ActionEvent evt=new ActionEvent(this,1,"HTML");
    if(canvas.isVisible())
    canvas.actionPerformed(evt);
    else
    backcanvas.actionPerformed(evt);
    //Paint of Applet
    public void paint(Graphics g)
    super.paint(g);
    //Update of Applet
    public void update(Graphics g)
    paint(g);
    //A panel Implemented to have Images Drawn on it
    static class ShapeCanvas extends JPanel implements ActionListener, MouseListener, MouseMotionListener,Runnable
    ArrayList shapes = new ArrayList();
    Color currentColor = Color.red;
    Image limg;
    BufferedImage bimg = new BufferedImage(430,400,BufferedImage.TYPE_INT_ARGB);
    Thread t = new Thread(this);
    ShapeCanvas(Image img)
    limg = img;
    addMouseListener(this);
    addMouseMotionListener(this);
    this.setBackground(Color.white);
    // t.start();
    zx = this.size().width / 2;
    zy = this.size().height / 2;
    zwidth = limg.getWidth(this);
    zheight =limg.getHeight(this);
    System.out.println("The parameter are"+zwidth+"and"+zheight);
    t.start();
    public void run()
    try
    for(int i=0;i<25;i++)
    repaint();
    t.sleep(250);
    repaint();
    catch(InterruptedException iee)
    public void updateComponent(Graphics g)
    paintComponent(g);
    public void deleteit(Shape shapetodelete)
    if(shapeBeingEdited != null)
    shapes.remove(shapeBeingEdited);
    repaint();
    public void paintComponent(Graphics go)
    //System.out.println("Called");
    super.paintComponent(go);
    go.drawImage(bimg,0,0,this);
    Graphics g = bimg.getGraphics();
    g.setColor(getBackground());
    g.drawRect(0,0,getSize().width,getSize().height);
    g.fillRect(0,0,getSize().width,getSize().height);
    g.drawImage(limg,0,0,this);
    /*zx = limg.size().width / 2;
    zy = this.size().height / 2;
    zwidth = limg.getWidth(this);
    zheight =limg.getHeight(this);*/
    zwidth *= scalingfactor;
    zheight *= scalingfactor;
    zx -= zwidth / 2;
    zy -= zheight /2;
    System.out.println("The values are"+zwidth);
    g.drawImage(limg, zx, zy, zwidth, zheight, this);
    int top = shapes.size();
    for (int i = 0; i < top; i++)
    s = (Shape)shapes.get(i);
    s.draw(g);
    g.dispose();
    go.dispose();
    public void actionPerformed(ActionEvent evt)
    //System.out.println(evt.getActionCommand());
    if(addnew == 1)
    //System.out.println("in new obj addnew "+ addnew);
    currentColor=Color.decode("1024");
    if(txtimgflag==0)
         System.out.println("string Function called");
    addShape(new StringShape(stringToDraw,fontmain,colormain,frocolor,msg,size,angle,str1,str2));
    else if(txtimgflag == 1)
    System.out.println("image function called");
    addShape(new ImageShape(someimg2));
    else if(txtimgflag==2)
    addShape(new ImageString(stringToDraw,fontmain,colormain,angle,size));
    System.out.println("txtimgflag in if else="+txtimgflag);
    else if(txtimgflag==3)
    addShape(new StyledString(stringToDraw,colormain,angle,size,str1,str2));
    System.out.println("txtimgflag in if else="+txtimgflag);
    repaint();
    void addShape(Shape shape)
    shape.setColor(currentColor);
    if(txtimgflag == 0)
    shape.reshape(150,80,100,20);
    shapes.add(shape);
    else if(txtimgflag == 1)
    shape.reshape(150,50,shape.width,shape.height);
    shapes.add(shape);
    else if(txtimgflag == 2)
    shape.reshape(150,50,100,100);
    shapes.add(shape);
    System.out.println("Image shape="+txtimgflag);
    else if(txtimgflag == 3)
    shape.reshape(150,60,100,100);
    shapes.add(shape);
    System.out.println("Image shape="+txtimgflag);
    repaint();
    Shape shapeBeingDragged = null;
    int prevDragX;
    int prevDragY;
    public boolean handleEvent (Event e)
    System.out.println("In zooming section");
    switch (e.id)
    case (Event.MOUSE_DOWN):
    oldy = e.y;
    return super.handleEvent(e);
    case (Event.MOUSE_UP):
    if (oldy > e.y)
    scalingfactor += (float) .1;
    else scalingfactor -= (float) .1;
    if (scalingfactor > (float) 5.0)
    scalingfactor = (float)5.0;
    if (scalingfactor < (float) .1)
    scalingfactor = (float).1;
    oldy = e.y;
    repaint();
    return super.handleEvent(e);
    default:
    return super.handleEvent(e);
    public void mousePressed(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    for ( int i = shapes.size() - 1; i >= 0; i-- )
    Shape s = (Shape)shapes.get(i);
    if (s.containsPoint(x,y))
    shapeBeingDragged = s;
    shapeBeingDraggedtemp =s;
    shapeBeingEdited = s;
    prevDragX = x;
    prevDragY = y;
    // shapeBeingEdited = s;
    if(shapeBeingEdited instanceof ImageShape)
    try
    Object obj[] = new Object[2];
    obj[0]=new Integer(((ImageShape)shapeBeingEdited).width);
    obj[1]=new Integer(((ImageShape)shapeBeingEdited).height);
    js.call("setValuesimg",obj);
    System.out.println("found Image shape");
    catch (JSException ex)
    else if(shapeBeingEdited instanceof StringShape)
    try
    String foreColor=Integer.toHexString(((StringShape)shapeBeingEdited).Mycolor.getRGB() );
    foreColor=( foreColor.substring(2)).toUpperCase();
    String backColor=Integer.toHexString(((StringShape)shapeBeingEdited).frcolor.getRGB() );
    backColor=( backColor.substring(2)).toUpperCase();
    //System.out.println("found string shape");
    Object obj[] = new Object[7];
    obj[0] = ((StringShape)shapeBeingEdited).Mystring;
    obj[1] = ((StringShape)shapeBeingEdited).Myfont.getFontName();
    obj[2] = foreColor;
    obj[3] = ((StringShape)shapeBeingEdited).msg;
    obj[4] = backColor;
    obj[5] = ((StringShape)shapeBeingEdited).Siz;
    obj[6] = ((StringShape)shapeBeingEdited).ang;
    js.call("setValues",obj);
    catch (JSException ex)
    else if(shapeBeingEdited instanceof ImageString)
    System.out.println("bulls eye");
    if (evt.isShiftDown())
    shapes.remove(s);
    shapes.add(s);
    repaint();
    if(evt.isAltDown())
    shapes.remove(s);
    repaint();
    else
    l1.setText("");
    if(evt.isControlDown())
    if(s instanceof ImageShape)
    if(evt.getButton() == MouseEvent.BUTTON1)
    s.htwt((s.width+1),(s.height+1));
    repaint();
    else if(evt.getButton() == MouseEvent.BUTTON3)
    s.htwt((s.width-1),(s.height-1));
    repaint();
    return;
    }//end of if
    else
    //shapeBeingEdited = null;
    public void mouseDragged(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    if (shapeBeingDragged != null)
    shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
    prevDragX = x;
    prevDragY = y;
    repaint();
    /*if(globalGrahics == null)
    System.out.println("globalGrahics is null ");
    globalGrahics = this.getGraphics();
    else
    globalGrahics.setColor(Color.CYAN);
    globalGrahics.drawRect(shapeBeingEdited.left,shapeBeingEdited.top,shapeBeingEdited.width+10,shapeBeingEdited.height);
    public void mouseReleased(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    if (shapeBeingDragged != null) {
    shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
    if ( shapeBeingDragged.left >= getSize().width || shapeBeingDragged.top >= getSize().height ||
    shapeBeingDragged.left + shapeBeingDragged.width < 0 ||
    shapeBeingDragged.top + shapeBeingDragged.height < 0 )
    //shapes.remove(shapeBeingDragged);
    if(x <=20 || y <= 20 || x >340 || y >330)
    shapeBeingDragged.left = (150);
    shapeBeingDragged.top = (100);
    repaint();
    shapeBeingDragged = null;
    repaint();
    public void mouseEntered(MouseEvent evt){repaint();}
    public void mouseExited(MouseEvent evt){}
    public void mouseMoved(MouseEvent evt)
    if(evt.isControlDown())
    l1.setText("Left Click on Image to Zoom in , Right to Zoom out");
    else if(evt.isAltDown())
    l1.setText("Click on Image or Text to Delete");
    else if(evt.isShiftDown())
    l1.setText("Click on Image to bring it forward");
    else
    l1.setText("");
    public void mouseClicked(MouseEvent evt)
    int x = evt.getX();
    int y = evt.getY();
    if(evt.getClickCount()>=2)
    for ( int i = shapes.size() - 1; i >= 0; i-- )
    Shape s = (Shape)shapes.get(i);
    if (s.containsPoint(x,y))
    shapeBeingEdited = s;
    }//end of shapeCanvas
    static abstract class Shape
    int left, top;
    int width, height;
    Color color = Color.white;
    void reshape(int left, int top, int width, int height)
    this.left = left;
    this.top = top;
    this.width = width;
    this.height = height;
    void htwt(int width,int height)
    this.width = width;
    this.height = height;
    void moveBy(int dx, int dy)
    left += dx;
    top += dy;
    void setColor(Color color)
    this.color = color;
    boolean containsPoint(int x, int y)
    if (x >= left && x < left+width && y >= top && y < top+height)
    return true;
    else
    return false;
    abstract void draw(Graphics g);
    }//end of abstarct shape class
    static class StringShape extends Shape
    String Mystring;
    Font Myfont ;
    Color Mycolor;
    Color frcolor;
    String msg="",font;
    Integer Siz,ang;
    int font_size;
    int w,size,angle,w1,style;
    int speed= 12;
    StringShape(String lstr,Font lfont,Color lcolor,Color lfcolor,String lmsg,int lsiz,int lang,String lfon,int lsty)
    Mystring = lstr;
    Myfont = lfont;
    Mycolor = lcolor;
    frcolor = lfcolor;
    size=lsiz;
    msg = lmsg;
    angle=lang;
    Siz= new Integer(lsiz);
    style=lsty;
    font=lfon;
    System.out.println("In the String shape");
    int ShiftNorth(int p, int distance)
    return (p - distance);
    int ShiftSouth(int p, int distance)
    return (p + distance);
    int ShiftEast(int p, int distance)
    return (p + distance);
    int ShiftWest(int p, int distance)
    return (p - distance);
    BufferedImage bimg,temp,bimg1,bimg2,bimg3;
    void draw(Graphics g)
    g.setColor(Mycolor);
    g.setFont(this.Myfont);
    int wt=g.getFontMetrics().stringWidth(Mystring);
    int ht=g.getFontMetrics().getHeight();
    this.htwt(wt,ht);
    int h1=size ;
    temp = new BufferedImage(10,10,BufferedImage.TYPE_INT_ARGB);
    Graphics lgimg = temp.getGraphics();
    Graphics2D gimg = (Graphics2D)lgimg;
    gimg.setFont(Myfont);
    gimg.setColor(Mycolor);
    int w2=g.getFontMetrics().stringWidth(Mystring);
    int len=Mystring.length();
    int w1=(w2*len);
    this.htwt(w1,w2);
    System.out.println("The length"+len);
    bimg = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    temp=null;
    lgimg = bimg.getGraphics();
    gimg = (Graphics2D)lgimg;
    gimg.setFont(Myfont);
    gimg.setColor(Mycolor);
    if(msg.equals("outlined"))
    w2=g.getFontMetrics().stringWidth(Mystring);
    System.out.println("tWidth"+w2+"theight"+h1);
    len=Mystring.length();
    w1=(w2*len);
    bimg1 = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    lgimg = bimg1.getGraphics();
    gimg = (Graphics2D)lgimg;
    System.out.println("Message --> " + msg);
    gimg.setColor(Mycolor);
    gimg.drawString(this.Mystring, ShiftWest((left+5), 1), ShiftNorth((top+Myfont.getSize()), 1));
    gimg.drawString(this.Mystring, ShiftWest((left+5), 1), ShiftSouth((top+Myfont.getSize()), 1));
    gimg.drawString(this.Mystring, ShiftEast((left+5), 1), ShiftNorth((top+Myfont.getSize()), 1));
    gimg.drawString(this.Mystring, ShiftEast((left+5), 1), ShiftSouth((top+Myfont.getSize()), 1));
    g.drawImage(bimg1,left+5,top,null);
    gimg.setColor(frcolor);
    gimg.drawString(this.Mystring, ShiftEast((left+5), 1), ShiftSouth((top+Myfont.getSize()), 1));
    g.drawImage(bimg1,left+5,top,null);
    else if(msg.equals("segment"))
    System.out.println("Message --> " + msg);
    int w = (g.getFontMetrics()).stringWidth("Segment");
    int h = (g.getFontMetrics()).getHeight();
    int d = (g.getFontMetrics()).getDescent();
    g.setColor(Mycolor);
    g.drawString(this.Mystring, (left+5), (top+Myfont.getSize()));
    g.setColor(frcolor);
    for (int i = 0; i < h; i += 3)
    g.drawLine((left+5), (top+Myfont.getSize()) + d - i, (left+wt) + w, (top+Myfont.getSize()) + d - i);
    else if(msg.equals("3d"))
    w2=g.getFontMetrics().stringWidth(Mystring);
    System.out.println("tWidth"+w2+"theight"+h1);
    len=Mystring.length();
    w1=(w2*len);
    bimg2 = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    lgimg = bimg2.getGraphics();
    gimg = (Graphics2D)lgimg;
    Color top_color = new Color(200, 200, 0);
    System.out.println("Message --> " + msg);
    for (int i = 0; i < 5; i++)
    gimg.setColor(top_color);
    gimg.drawString(this.Mystring, ShiftEast((left+4), i), ShiftNorth(ShiftSouth((top+Myfont.getSize()), i), 1));
    gimg.setColor(frcolor);
    gimg.drawString(this.Mystring, ShiftWest(ShiftEast((left+4), i), 1), ShiftSouth((top+Myfont.getSize()), i));
    gimg.setColor(Mycolor);
    gimg.drawString(this.Mystring, ShiftEast((left+4), 5), ShiftSouth((top+Myfont.getSize()), 5));
    g.drawImage(bimg2,left+10,top,null);
    else if(msg.equals("flow"))
    System.out.println("Message"+msg);
    int len1=Mystring.length();
    int lsize=size;
    int lleft =25;
    int ltop = g.getFontMetrics().getHeight();
    w1=g.getFontMetrics().stringWidth(Mystring);
    System.out.println("The value of w1 is"+w1);
    for(int j=0;j<Mystring.length();j++)
         w1=w1+size;
         System.out.println("Size"+w1);
    bimg3 = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    lgimg = bimg3.getGraphics();
    gimg = (Graphics2D)lgimg;
    gimg.setFont(new Font(font,style,lsize));
    gimg.setColor(Mycolor);
    for (int i = 0; i<Mystring.length(); i++)
    gimg.setFont(new Font(font,style,lsize));
    ltop= ltop+5;
    gimg.drawString(""+Mystring.charAt(i),lleft,ltop);
    //gimg.drawRect(lleft,ltop-20,gimg.getFontMetrics().charWidth(Mystring.charAt(i)),gimg.getFontMetrics().getHeight());
    lleft=lleft+gimg.getFontMetrics().charWidth(Mystring.charAt(i));
    lsize = lsize + 5;
    g.setColor(Mycolor);
    // g.drawRect(left+5,top,bimg.getWidth(),bimg.getHeight());
    g.drawImage(bimg3,left+5,top,null);
    else
         // g.drawString(this.Mystring,(left+5),(top+Myfont.getSize()));
    gimg.drawString(Mystring,30,10);
    g.drawImage(bimg,left+10,top,null);
    }//end of Draw Function
    static class ImageShape extends Shape
    Image someimg;
    ImageShape(Image lsomeimg)
    someimg = lsomeimg;
    width = someimg.getWidth(null);
    height = someimg.getHeight(null);
    System.out.println("constr width "+width+ " height"+ height);
    this.htwtimg(width,height);
    void htwtimg(int width,int height)
    this.width = width;
    this.height = height;
    System.out.println("its from image");
    void draw(Graphics g)
    g.drawImage(this.someimg,left,top,width,height,io);
    }//END OF IMageShape Class
    static class ImageString extends Shape
    String bstring;
    int ang,siz;
    Font lfont;
    Color lcolor;
    ImageString(String istr,Font lfon,Color lclr,int lang,int lsiz)
         bstring=istr;
         ang=lang;
         siz=lsiz;
         lfont=lfon;
         lcolor=lclr;
    BufferedImage bimg,temp;
    public void draw(Graphics g)
    int h=siz;
    temp = new BufferedImage(10,10,BufferedImage.TYPE_INT_ARGB);
    Graphics lgimg = temp.getGraphics();
    Graphics2D gimg = (Graphics2D)lgimg;
    gimg.setFont(lfont);
    System.out.println("Font is"+lfont);
    gimg.setColor(lcolor);
    int w=g.getFontMetrics().stringWidth(bstring);
    System.out.println("tWidth"+w+"theight"+h);
    int len=bstring.length();
    int w1=(w*len);
    System.out.println("The length"+len);
    bimg = new BufferedImage(w1,w1,BufferedImage.TYPE_INT_ARGB);
    temp=null;
    lgimg = bimg.getGraphics();
    gimg = (Graphics2D)lgimg;
    gimg.setFont(lfont);

    can you tell in short what are you doing and what you wish to do.

  • Help please, not able to load images in a subclass of a japplet

    I've created this board for a project, but now I am stuck, I cannot seem to get images to appear, instead they come up as a nullpointerexception:
    public class Board extends JLayeredPane implements MouseListener, MouseMotionListener{
         private Container contentPane;
         private JLayeredPane jlp;     
         private boolean pieceSelected;
         private timepanel time;
         Image bimage;
         ImageIcon board;
         JLabel brd;
         Image pimage;
         ImageIcon piece;
         JLabel pce;
         private Graphics g;
         private pieceLayout pieces;
         private String piecename;
         private JLabel jl;
         boolean selected;
         private int offset;
         boolean changepos;
         boolean moving;
         private int brdwidth;
         private int brdheight;
         private Timer countdown;
         private updateTimer ut;
         private String cb;
         private clientinterface ci;
         private JFrame j;
         private int playerturn;
         public Board(clientinterface ci, JFrame j, Hashtable images, ArrayList names,
         ImageIcon brdicon, URL cb)
              j.setSize(500,450);
              countdown = new Timer();
              selected = false;
              jlp = this;
              jlp.setPreferredSize(new Dimension(500, 450));
              changepos = false;
              //contentPane = getContentPane();
              //this.setPreferredSize(new Dimension(500,400));
              jlp.setBounds(0,0,500,450);
              jlp.setLocation(0,0);
              jlp.setOpaque(true);
              jlp.setLayout(null);
              System.out.println(this.getSize() + "(((())))" );
              if(j.getWidth() > 400)
                   offset = j.getWidth() - 400;
              else
                   offset = 0;
              System.out.println("Width is: " +  j.getWidth() + " height: " + j.getHeight());     
              brdwidth = j.getWidth()-offset;
              brdheight = j.getHeight();
              System.out.println(images.size());     
              System.out.println(j.getWidth() + " " + j.getHeight() + " " + offset);
              brd = new JLabel(brdicon);
              brd.setBounds(0,0,j.getWidth()-offset, j.getHeight());
              brd.setSize(new Dimension(400,400));
              brd.setLocation(0,0);
              brd.setOpaque(true);
              jlp.add(brd, new Integer(-5));
              jlp.setBounds(0,0,j.getWidth(), j.getHeight());
              jlp.setVisible(true);
              time = new timepanel(jlp);
              time.setLocation(j.getWidth()-offset, 0);
              System.out.println(images.toString() + "++++++++");
              pieces = new pieceLayout(jlp, j.getWidth()-offset, names, cb);
              pieces.setLocation(0,0);
              pieces.setPreferredSize(new Dimension(400,400));
              pieces.setBounds(0,0,400,400);
              pieces.setVisible(true);
              time.setBounds(400,0, 100, 400);
              time.setVisible(true);
              ut = new updateTimer(time);
              jlp.add(pieces, new Integer(2));
              jlp.add(time, new Integer(2));
              //this.add(jlp);
              j.setLayeredPane(jlp);
              addMouseMotionListener(this);
              addMouseListener(this);
              //j.getContentPane().add(jlp);
              //j.setContentPane(this);
              j.validate();
              //j.getContentPane().setLayout(null);
              //j.setContentPane(this);
              j.paintAll(j.getGraphics());
         public void run()
              //this.repaint();
              this.paintAll(this.getGraphics());
              time.repaint();
         public void mouseDragged(MouseEvent e)
              JLabel temp;
              moving = true;
              //pce.setLocation(e.getX(), e.getY());
              //pieces.getPiece(pieces.translatecoords(e.getX(),e.getY())).setLocation(e.getX(),e.getY());
              int piecepos = pieces.translatecoords(e.getX(), e.getY());
              /*if(pieces.hasPiece(piecepos) && moving)
                   pieces.setSelected(piecepos);
                   temp = pieces.getPiece(piecepos);
                   //pieces.movePiece(e.getX(), e.getY());
                   temp.setLocation(e.getX(), e.getY());
              //this.repaint();
         public void mouseClicked(MouseEvent e)
              Point xpoin;
              System.out.println("Hello, clicked");
              /*pce.setLocation(e.getX(), e.getY());
              Point p = pce.getLocation();
              System.out.println(p.toString());*/
              System.out.println("\n" + e.getX() + " " + e.getY());
         public void mouseEntered(MouseEvent e)
         public void mouseExited(MouseEvent e)
         public void mouseReleased(MouseEvent e)
              if(selected)
                   Point xp;
                   int x = e.getX();
                   int y = e.getY();
                   int bp = pieces.translatecoords(x,y);
                   xp = pieces.posToPoint(bp);
                   pieces.snapToSquare(xp.x, xp.y, bp);
                   selected = false;
                   moving = false;
                   //pieces.updateBoard(bp, piecename);
         public void mouseMoved(MouseEvent e)
         public void mousePressed(MouseEvent e)
              Point xpoin;
              int pos = pieces.translatecoords(e.getX(),e.getY());
              System.out.println("\n" + pieces.translatecoords(e.getX(),e.getY()));
              if(pieces.hasPiece(pos, e.getX(), e.getY()))
                        piecename = pieces.getName(pos);
                        System.out.println("Found a piece!");
                        pieces.setSelected(pos);
                        xpoin = pieces.posToPoint(pos);
                        selected = true;
         public void paintComponent(Graphics g)
              //super.paintComponents(g);
              //System.out.println("Painting");
              time.repaint();
         public void start()
              countdown.schedule(ut, 0, 1000);
         public void setupBoard()
                   //setSize(getSize().width < 400 ? 400 : getSize().width,
                   //getSize().height < 400 ? 400 : getSize().height);
                   //getLayeredPane().add(brd, new Integer(-5));
         public void sendInfo(String info)
              //parse information
         public class pieceLayout extends JLayeredPane
              JLabel pce1;
              private JLabel selected;
              private Hashtable pieceList;
              private ArrayList names;
              private int width;
              private Hashtable piecesOnBoard;
              private char boardstate[]= {'R','N','B','Q','K','B','N','R',
                                                 'P','P','P','P','P','P','P','P',
                                                 'p','p','p','p','p','p','p','p',
                                                 'r','n','b','q','k','b','n','r'
              private String posnm[]       = {
                                                       "a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8",
                                                       "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7",
                                                       "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6",
                                                       "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5",
                                                       "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4",
                                                       "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3",
                                                       "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2",
                                                       "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1"
              JLayeredPane thePane;
              private Hashtable ht;
              private Hashtable board;
              private Hashtable b2p;
              private Hashtable p2b;
              private Hashtable piecePos;
              private Hashtable objToName;
              private Hashtable posnames;
              private URL codebase;
              public pieceLayout(JLayeredPane p, int twidth, ArrayList pnames, URL cb)
                   pieceList = new Hashtable(20);
                   codebase = cb;
                   names = pnames;
                   selected = new JLabel();
                   piecesOnBoard = new Hashtable(32);
                   ht = new Hashtable(6);
                   board = new Hashtable(64);
                   b2p = new Hashtable(64);
                   p2b = new Hashtable(64);
                   piecePos = new Hashtable(64);
                   objToName = new Hashtable(32);
                   posnames = new Hashtable(64);
                   fillnames();
                   getImages();
                   setImages();
                   width = twidth;
                   thePane = p;
                   System.out.println(piecesOnBoard.size());
                   showBoard();
              private void fillnames()
                   int size = posnm.length;
                   for(int i = 0; i < size; i++ )
                        posnames.put(new Integer(i), new String(posnm));
                   showPos();
              private void getImages()
                   Pattern p = Pattern.compile(".+\\.GIF");
                   Pattern p1 = Pattern.compile(".+\\.gif");
                   Pattern p2 = Pattern.compile("board.+");
                   Pattern p3 = Pattern.compile(".+board.+");
                   for(int i = 0; i < names.size(); i++)
                        Matcher m = p.matcher((String)names.get(i));
                        Matcher m1 = p1.matcher((String)names.get(i));
                        Matcher m2 = p2.matcher((String)names.get(i));
                        Matcher m3 = p3.matcher((String)names.get(i));
                        if(m.matches() || m1.matches())
                             //System.out.println("Files are: " + dirs[i].getName());
                             if(!m2.matches() && !m3.matches())
                                  String piecename = new String((String)names.get(i));
                                  //     System.out.println("Files were: " + dirs[i].getName());
                                  Image tpimage = Toolkit.getDefaultToolkit().createImage(piecename);
                                  Image pimage = tpimage.getScaledInstance(35,35, Image.SCALE_DEFAULT);
                                  //ImageIcon piece = new ImageIcon(pimage);
                                  pieceList.put(new String(piecename), pimage);
                   System.out.println(pieceList.toString());
                   System.out.println(pieceList.size() + "((**))(())");
              private void setImages()
                   int listsize = names.size();
                   if(!pieceList.isEmpty())
                        int index = 0;
                        for(int i = 0; i < listsize; i++)
                             String pieceName = (String)names.get(index);
                             String hKey = getHashKey(pieceName);
                             System.out.println(hKey);
                             if((hKey.compareTo("blackking") == 0) || (hKey.compareTo("blackqueen") == 0) ||
                             (hKey.compareTo("whiteking") == 0) || (hKey.compareTo("whitequeen") == 0))
                                  Image tpiece = (Image)pieceList.get(new String(hKey));
                                  ImageIcon piece = new ImageIcon(tpiece);
                                  pce1 = new JLabel(piece);
                                  piecesOnBoard.put(new String(hKey), pce1);
                             else
                                  System.out.println("multiples " + hKey);
                                  createMultiples(hKey, pieceName);
                             if(i == listsize-1)
                                  index = 0;
                             else
                                  index++;
                             System.out.println(pieceName + " " + hKey + "1234567890");
              private void createMultiples(String key, String hname)
                   JLabel piecet;
                   String name;
                   if(key == "blackpawn" || key == "whitepawn")
                        name = key;
                        for(int i = 0; i < 8; i++)
                             //System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                   else if(key == "blackknight" || key == "whiteknight")
                        name = key;
                        for(int i = 0; i < 2; i++)
                             //System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                        if(!ht.containsKey(new String(key)))
                             ht.put(new String(key+0), new Integer(0));
                   else if(key == "blackbishop" || key == "whitebishop")
                        name = key;
                        for(int i = 0; i < 2; i++)
                             System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             System.out.println(piece.toString());
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                        if(!ht.containsKey(new String(key)))
                             ht.put(new String(key+0), new Integer(0));
                   else if(key == "blackrook" || key == "whiterook")
                        name = key;
                        for(int i = 0; i < 2; i++)
                             System.out.println(name+i);
                             String tempname = name+i;
                             Image piece = (Image)pieceList.get(new String(name));
                             ImageIcon pieces = new ImageIcon(piece);
                             piecet = new JLabel(pieces);
                             piecesOnBoard.put(new String(tempname), piecet);
                        if(!ht.containsKey(new String(key)))
                             ht.put(new String(key+0), new Integer(0));
    Hopefully this will format alright, but my question is, is that why is it giving me this error... it happens in the create multiples function(the last function in this code block) this is a jlayeredpane which is called by a JApplet. Any ideas on the loading? Its in the getImages() fuction.

    These are the lines it dies on.... the System.out.println(piece.toString()); precisely. I don't know if I am not getting the images from the directory right... or if I need to make sure this is in a JAR file or not.
    {                    name = key;                    for(int i = 0; i < 2; i++)                    {                         System.out.println(name+i);                         String tempname = name+i;                         Image piece = (Image)pieceList.get(new String(name));                         System.out.println(piece.toString());                         ImageIcon pieces = new ImageIcon(piece);                         piecet = new JLabel(pieces);                         piecesOnBoard.put(new String(tempname), piecet);                    }                    if(!ht.containsKey(new String(key)))                    {                         ht.put(new String(key+0), new Integer(0));                    }                    

  • Load Image into JApplet

    Hello to all Java expect coder, i would like to load an image to an applet but after it flash once time then it just disappear.
    Below is my code :
    * SodaVendingMachineApplet.java
    * Created on June 8, 2008, 4:08 PM
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.ImageIcon.*;
    * @author  nicholas_tse
    public class SodaVendingMachineApplet extends javax.swing.JApplet {
        private ImageIcon  soda;
        private ImageIcon  lemon;
        private ImageIcon  orange;
        private Graphics g;
         // To draw image
        @Override
        public void paint(Graphics g)
            soda = new ImageIcon("D:/Java/SodaMachine/cola_5.jpg");
            soda.paintIcon(this, g, 30, 40);
        /** Initializes the applet SodaVendingMachineApplet */
        @Override
        public void init() {
            try {
                java.awt.EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        initComponents();
            } catch (Exception ex) {
                ex.printStackTrace();
        /** This method is called from within the init() method to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jRadioButton1 = new javax.swing.JRadioButton();
            jRadioButton2 = new javax.swing.JRadioButton();
            jRadioButton3 = new javax.swing.JRadioButton();
            jRadioButton4 = new javax.swing.JRadioButton();
            jRadioButton5 = new javax.swing.JRadioButton();
            jRadioButton6 = new javax.swing.JRadioButton();
            jLabel1.setText("Soda");
            jLabel2.setText("Lemon");
            jLabel3.setText("Orange");
            jRadioButton1.setText("Regular");
            jRadioButton2.setText("Diet");
            jRadioButton3.setText("Regular");
            jRadioButton4.setText("Diet");
            jRadioButton5.setText("Regular");
            jRadioButton6.setText("Diet");
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(16, 16, 16)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jRadioButton2)
                                    .addGap(18, 18, 18))
                                .addComponent(jRadioButton1)))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(38, 38, 38)
                            .addComponent(jLabel1)))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(61, 61, 61)
                            .addComponent(jLabel2))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(49, 49, 49)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jRadioButton4)
                                .addComponent(jRadioButton3))))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(47, 47, 47)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jRadioButton6)
                                .addComponent(jRadioButton5)))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(63, 63, 63)
                            .addComponent(jLabel3)))
                    .addContainerGap(107, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(69, 69, 69)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jRadioButton1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jRadioButton2))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jRadioButton3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jRadioButton4))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jRadioButton5)
                            .addGap(23, 23, 23))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(23, 23, 23)
                            .addComponent(jRadioButton6)))
                    .addContainerGap(175, Short.MAX_VALUE))
        }// </editor-fold>                       
        // Variables declaration - do not modify                    
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JRadioButton jRadioButton1;
        private javax.swing.JRadioButton jRadioButton2;
        private javax.swing.JRadioButton jRadioButton3;
        private javax.swing.JRadioButton jRadioButton4;
        private javax.swing.JRadioButton jRadioButton5;
        private javax.swing.JRadioButton jRadioButton6;
        // End of variables declaration                  
    }The image just flash once.
    I create using NetBeans IDE via JApplet forms.
    I know how to createa button and don't know how to adjust the location. Please help.
    Thanks for your help.

    In the future, Swing related questions should be posted in the Swing forum.
    Swing is different than AWT. The design of your applet is wrong.
    You should not be overriding the paint() method of the applet.
    In Swing you add components to the content pane. So in your case you would add a JPanel with your image to the content pane of the applet.
    Search the Swing forum and you will find examples of adding a "background image" to a panel.
    I know how to createa button and don't know how to adjust the location. Please help. Then don't use an IDE. Learn how to Layout Managers and design the GUIs on your own. Spend your time learning Java, not the IDE.
    Read the JButton API and you will find a link to the Swing tutorial that give an example of using buttons on a frame.

  • Background image for a JApplet

    Hi everybody.
    I have a app with some textfields, buttons and some JLabels.
    I want to put a image as background.
    How can I do that?
    Thanks in advance.

    JApplet (and JFrame and any root container) has a Container that it uses to hold everything else, its contentPane. I would create a JPanel and make it my applet's contentPane and then add everything to this contentPane. To show an image on the contentPane/JPanel, I'd simply Google Background image jpanel. I'd get and then read this: [http://faq.javaranch.com/java/BackgroundImageOnJPanel]
    (I've actually bookmarked this page as it gets asked here so often).

  • Images in JApplet

    Hi!
    I am trying to convert a game application, made using Java - Swing combination, to an JApplet.
    First I installed the newest JRE1.3.1 from the java.sun.com and used the HTMLConverter.
    Testing revealed that the JApplet runs quite Ok in the Appletviewer.
    When I try to run it in Netscape 6.1 the game works otherwice except that it doesn't have any
    of it's pictures which are either in gif - or jpg formats. The Java Console doesn't tell me anything that might indicate a problem.
    The interesting part comes when I try to run the same JApplet inside IE5.5. I get a message
    that states that the requested html-page (or one of its components) could not be found. At the
    same time thought an instance of the Netscape 6.1 is being launched and, to my surprise, the
    JApplet runs Ok in it.
    If I try to run the JApplet in Opera 5.12 I just get a message saying that a connection to the
    running virtual machine could not be established.
    At home I use Linux and KDE's browser Konqueror. That's the only one that gives a securityexception for the read operation of the images.
    At work, where I have Win 2000, I have tried to play with policytool in order to grant the required reading permissions, but I haven't succeeded yet.
    I would appreciate any help in solving this mystery.
    Jussi

    Image         map;
    URL url = null;
    try
             url = new URL(getCodeBase()+"usa.gif");
         catch(MalformedURLException e)
    map = getToolkit().createImage(url);
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(map,0);
    try   {tracker.waitForID(0);}
    catch (InterruptedException e){} .
    //usa.gif is the name of the file
    Noah

Maybe you are looking for