GetImage() in JApplet

Hi folks!
Can anybody help me here - I'm trying to use the getImage() method of JApplet to load images into my Applet (the images required are dependent on info received from a JDBC / Network connection so I want to be selective about the images I load). I know the getImage() method only works during the execution of the Applet's init(). However I have looked on the JApplet FAQ in the tutorial and it states it can be called after init() has finished. Is this possible and, if so, how 'cos I can't get it to work?!? I will need to call getImage() from a method totally independent from init()...
Any help would be appreciated...

Hi,
you can try the blow code. in any AWT or Swing component. But the image url must from the same server that applet's.
java.awt.Toolkit.getDefaultToolkit().getImage(new URL("the image url"));

Similar Messages

  • JApplet getImage problem

    hi!
    I have
    public class myapplet extends JAppletclass and I`m trying to load image inside init() method:
    Image img = getImage(getDocumentBase(), "x.jpeg");File "x.jpeg" exist, and I am sure that it is in right place. But after getImage() img variable is wrong initiate, his height and width have -1 value.
    I have trying run this code under eclipce applet simulator and on server, but in both case it didn`t work.
    What is the problem?
    bye!

    The loading is asynchronous... You need to refresh your data until the image is loaded, or wait for the image to be loaded to get them :
    Image img = getImage(getDocumentBase(), "x.jpeg");
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(img,0);
    mt.waitForId(0);
    int w = img.getWidth(this);
    int h = img.getHeight(this);

  • Need help importing animated gif by ImageIcon in Japplet

    Hello. Im new to Java, but I want to import this animated gif with Java in a Japplet using ImageIcon, but it does not work and I would really appreciate if anyone could help me with this.
    import java.applet.*;                                   
    import java.awt.*;   
    import java.net.*;
         public class Bilder extends Japplet{                               
         public ImageIcon(java.net."http://pixelninja.se/kappawin.gif");
      Image[] bild = new Image[1];                            
      int nr=0;                                                
      public void init(){                                     
        setBackground(Color.black);                         
        bild[0] = getImage(getCodeBase(),"4a.gif");     
      public void paint(Graphics g){
        g.drawImage(bild[0],50,50,212,282,this);
    }

    You cant do animated gifs this way.
    Also you should remember that you cannot load images in to an applet if it is hosted somewere else than the host that hosts the applet.
    Esiast way to display an image icon with a animated gif will be creating a Image Label and adding it to the applet.
    Ex:-
    public class MyImageApplet extends JApplet{
       public void init(){
          getConentPane().setLayout(new BorderLayout());
           URL imageURL = getClass().getResource("/myImage.gif"); 
          // Above image file should be in the code base or in the archive file of the applet
          getConentPane().add(new JLabel(new ImageIcon(imageURL)));
    }

  • 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));                    }                    

  • JApplet won't switch image??

    Hi everyone...
    My JApplet was supposed to display a new image when the sign up button is pressed..
    But it doesn't.. Here take a look at my source code!
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.applet.*;
    public class JFrameApplet extends JApplet implements Runnable
    private Thread th;
    private Image icon;
    Image background;
      public void init()
    background = getImage(getCodeBase(), "background.gif");
        Container content = getContentPane();
        content.setLayout(new FlowLayout());
        JButton signUp = (new JButton("Sign Up"));
    JButton logIn = (new JButton("Login"));
    signUp.addActionListener(new ActionListener()
      public void actionPerformed(ActionEvent e)
       getIcon();
    content.add(signUp);
    content.add(logIn);
      private void getIcon()
      MediaTracker tracker = new MediaTracker(this);
      icon = getImage(getCodeBase(), "icon.png");
      tracker.addImage(icon, 1);
    try
      tracker.waitForAll();
    catch(Exception exception)
      System.out.println("Error displaying new image.");
      private void getImages()
      public void start()
    th = new Thread(this);
    th.start();
      public void destroy()
    th.stop();
      public void run()
      public void stop()
    th.stop();
      public void update(Graphics g)
      public void paint(Graphics g)
    g.drawImage(background, 0, 0, this);
    }

    Wow thanks, the following code helped my out :)
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.applet.*;
    public class JFrameApplet extends JApplet implements Runnable
    private Thread th;
    Image background, icon;
      public void init()
    background = getImage(getCodeBase(), "background.gif");
        Container content = getContentPane();
        content.setLayout(new FlowLayout());
        JButton signUp = (new JButton("Sign Up"));
    JButton logIn = (new JButton("Login"));
    signUp.addActionListener(new ActionListener()
      public void actionPerformed(ActionEvent evt)
       icon = getImage(getCodeBase(), "icon.gif");
    content.add(signUp);
    content.add(logIn);
    private void getImages()
    public void start()
        th = new Thread(this);
    th.start();
    public void destroy()
        th.stop();
    public void run()
    public void stop()
        th.stop();
    public void update(Graphics g)
    public void paint(Graphics g)
        g.drawImage(background, 0, 0, this);
    g.drawImage(icon, 0, 0, this);
    }Here you are, 5 duke stars!

  • JApplet and the Images --PLEASE reply fast

    the problem is i am trying to put a .gif image into JApplet. no matter what i do it just DOESNT WANNA WORK! can anyone please post an example of working one?

    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    import java.lang.Object.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.LineBorder.*;
    import javax.swing.border.*;
    import javax.swing.*;
    import java.awt.*;
    import java.applet.*;
    import java.util.Random;
    public class MoveTheSquare  extends JApplet implements ActionListener
         public static int size = 100;
           public     static        int life = 80;
            public     static       int eneLife=50;
         private AudioClip ohboy2= getAudioClip(getDocumentBase(), "ohboy2.wav");
    //      public Image bricks = getImage(getDocumentBase(),"bricks.gif");
        public static void main(String[] args)
            ApplicationFrame frame = new ApplicationFrame();
            frame.setBounds(50, 50, 900, 900);
            frame.setVisible(true);
            new ApplicationFrame();
        private static class ApplicationFrame extends JFrame
            public ApplicationFrame()
            super("Move the Sticky Figure!");
               // setDefaultCloseOperation(EXIT_ON_CLOSE);
                setSize(500, 600);
                JPanel content = new JPanel();
                ((JPanel) getContentPane()).setOpaque(true);
               // new WindowListener(1);
                 ImageIcon bricks = new ImageIcon("bricks.gif");
                 JLabel backlabel = new JLabel(bricks);
                getLayeredPane().add(backlabel, new Integer(Integer.MIN_VALUE));
                backlabel.setBounds(0,0,20000,2560);
                setLocation(500,600);
                  //WindowListener1 = new WindowAdapter() {
                  //public void windowClosing(WindowEvent e) {
                  //System.exit(0);
                  //setVisible(true);
                initUi();
            private void initUi()
                Container cp = getContentPane();
                Image img = getImage(getDocumentBase(), "bricks.gif" );
                cp.add(new MyPanel(img));
                cp.setLayout( new BorderLayout(0, 10) );
              //   addWindowListener1();
                cp.add( new JLabel(" Move the Sticky with the arrow keys:"), BorderLayout.NORTH );
                // Create the playing board and the squar
                Square sq = new Square( new Point(100, 100), 10 );
                Board board = new Board(sq);
                cp.add( board, BorderLayout.CENTER );
                // Register Key Bindings to move the square around. Read about the
                InputMap im = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
                ActionMap am = getRootPane().getActionMap();
                // The LEFT arrow will move the suare to pixels two the left
                MoveSquareAction moveLeft = new MoveSquareAction(board, -3, 0);
                KeyStroke keyStrokeLeft = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
                im.put( keyStrokeLeft, "left" );
                am.put( "left", moveLeft );
                // The RIGHT arrow will move the suare to pixels two the right
                MoveSquareAction moveRight = new MoveSquareAction(board, 3, 0);
                KeyStroke keyStrokeRight = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
                im.put( keyStrokeRight, "right" );
                am.put( "right", moveRight );
                // The UP arrow will move the suare two pixels up
                MoveSquareAction moveUp = new MoveSquareAction(board, 0, -3);
                KeyStroke keyStrokeUp = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
                im.put( keyStrokeUp, "up" );
                am.put( "up", moveUp );
                // The DOWN arrow will move the suare two pixels down
                MoveSquareAction moveDown = new MoveSquareAction(board, 0, 3);
                KeyStroke keyStrokeDown = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
                im.put( keyStrokeDown, "down" );
                am.put( "down", moveDown );
                pack();
        // Class that represents the playing board
        private static class Board extends JPanel
              private Square square;
            public Board(Square sq)
                square = sq;
                setOpaque(true);
                setBorder( new LineBorder(Color.GREEN));
            int x=1;
            public void  paintComponent(Graphics g)
                super.paintComponent(g);
                g.drawImage( img, currentX, currentY, this );
                   if (x==1)
                Point location = square.getLocation();
                String coordX = String.valueOf(location.x);
                String coordY = String.valueOf(location.y);
                String slife = String.valueOf(life);
                    //g.drawImage(bricks, 0, 0, 500, 16, this);
                  g.setColor(Color.red);
                   g.fillRect(240,240,250,250);
                   g.setColor(Color.GREEN);
                   g.fillRect(0,00,40,40);
                   g.setColor(Color.black);
                g.drawLine(location.x-5,location.y+5,location.x,location.y);
                   g.drawLine(location.x+5,location.y+5,location.x,location.y);
                   g.drawLine(location.x,location.y,location.x,location.y-7);
                   g.drawLine(location.x-4,location.y-4,location.x,location.y-7);
                   g.drawLine(location.x+4,location.y-4,location.x,location.y-7);
                   g.fillOval(location.x-3,location.y-15,8,8);
                   g.drawString(coordX,20,20);
                   g.drawString(coordY,20,30);
                   g.drawString("YOUR LIFE:", 00,70);
                   g.drawString(slife,70,70);
                   Random generator = new Random();
                  int takeaway = generator.nextInt(25);
                     int fight = generator.nextInt(50);
                   if (fight==4)
                  x=0;
                 life= life-takeaway;
                  JOptionPane.showMessageDialog(null, "YOU ARE BEING ATTACKED!!!!! YOU LOST HEALTH:" +takeaway);
                    slife = String.valueOf(life);
                 g.drawString(slife,70,70);
                 if (life<=0)
                 JOptionPane.showMessageDialog(null, "you lose. bye.");
                 System.exit(0);
                 if (((location.x>=240) && (location.y>=240)) &&((location.x<=490) && (location.y<=490)))
                 JOptionPane.showMessageDialog(null, "you Win! bye.");
                 System.exit(0);
           Random generator = new Random();
           int fight = generator.nextInt(50);
           if (fight==1)
           x=1;
            public Square getSquare()
                return square;
        // The Action class that implements moving the square:
        private static class MoveSquareAction extends AbstractAction
            // The board this action acts on:
            Board board;
            // The number of pixels to move in the X- and Y-directions:
            int pixelsToMoveX;
            int pixelsToMoveY;
            public MoveSquareAction(Board board, int pixelsToMoveX, int pixelsToMoveY)
                this.board = board;
                this.pixelsToMoveX = pixelsToMoveX;
                this.pixelsToMoveY = pixelsToMoveY;
            public void actionPerformed(ActionEvent e)
                // Move the square and repaint the board:
                board.getSquare().moveX(pixelsToMoveX);
                board.getSquare().moveY(pixelsToMoveY);
                board.repaint();
        // Class that represents the black square we move around
        private static class Square
            private Point     location;
            private int          size;
            public Square(Point loc, int size)
                location = loc;
                this.size = size;
            public Point getLocation()
                return location;
            public int getSize()
                return size;
            public void moveX(int pixels)
                location.x += pixels;
            public void moveY(int pixels)
                location.y += pixels;
        public void actionPerformed(ActionEvent e)
                 ohboy2.loop();//sound
    }

  • Re-painting in JApplet

    I'm trying to build a very simple picture browser from JApplet. There is just a picture, next, previous, last and first buttons.
    I have got the picture viewer working to a point. The program loads the default image to start. However if I click the first or last button the program will display the image but only after I click one of the scroll bars, the the correct image is loaded into the display.
    Here is a code sample to the first button ActionListener
    current = 0;
    thePic.setImage(new ImageIcon(theNames[0]).getImage());
    theTopTitle.setText("First Record (" + current + ")");     
    Does anyone know how to update the display when I click the button so the image is actually shown/updated? Do I need to use a Graphics object or paint method etc?
    thanks
    from Phil

    My experience of using graphics in Java is that it is always best to use a paint() method, as otherwise you seem to get all sorts of minor display artefacting. If you create a class that extends Canvas for your picture & then override paint() in this class, you can simply call repaint() when your button is pressed & the whole image should re-paint.
    Something like the following ( the update() method is only necessary if you wish to avoid display flicker ):
    (Initialise at start: )
    MapCanvas canvas = new MapCanvas( );
    (In your button method: )
    canvas.repaint( );
    class MapCanvas extends Canvas
    Image offScrImg;
    public void update( Graphics g )
    if( offScrImg == null ) { offScrImg = createImage( getSize( ).width, getSize( ).height ); }
    Graphics og = offScrImg.getGraphics( );
    paint( og );
    g.drawImage( offScrImg, 0, 0, this );
    og.dispose();
    public void paint( Graphics g )
    (Insert method to draw image here)
    }

  • PaintComponet(g) in Japplet? thanks- newbie here

    Hey guys, I have a JApplet with a series of jpanels. I would like to draw on the various panels independently. The forums have showed me that I need to use the paintComponent() method. well whenever i use the code..
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(pic.getImage(),0,0,this);
    }it says that Error(433,11): method paintComponent(java.awt.Graphics) not found in class javax.swing.JApplet . What am I doing wrong? Thanks in advance!!!

    paintComponent is a method of class JComponent.
    JApplet is not derived from JComponent.
    Even if it where, it would be a mistake to do that.
    JApplet's job is to be a container: it should not be doing the drawing.
    Define subclasses of JPanel to do your custom drawing, and have your JApplet function as it normally does.

  • How to make smooth hardware accelerated JApplet?

    Hi there ive made a game that extends JPanel and im using the paintComponent method to do my painting
    as far as i know JPanel is hardware accelerated by default bufferStrategy(2)
    ive put the JPanel in a JFrame and the game runs very smooth with ~62fps and cpu usage is <10%
    then i tried putting the JPanel in JApplet and opened it in firefoxbrowser and the fps says ~59fps and cpu usage ~30% but its super skippy and looks like its drawing incorrectly like some of the objects are displaced very far from where they are supposed to be some frames and drawn perfectly some other frames. What's happening? Is there anyway to fix this?
    Below is some code that for a JApplet and JFrame they both contain the JPanel and ive packed everything in a jar file that can be run as a desktopapp or japplet
    I've also tried add the JApplet directly into the JFrame but it seems the performance might go down a little (though im not sure how much)
    main extends JApplet
    RobotValkyrieAttack extends JPanel
    package RobotValkyrieAttack;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class main extends JApplet{
         static LinkedList<Image> listImage;
         //no JApplet constructor is allowed to be overrriden
         public void init(){ //called by the japplet container
              this.loadImages();
              RobotValkyrieAttack r = new RobotValkyrieAttack(listImage);
              this.add(r);
              Thread t = new Thread(r);
              t.start();
              this.addKeyListener(r);
         public void loadImages(){
              //images
              listImage = new LinkedList<Image>();
              listImage.add( new ImageIcon(this.getClass().getResource("data/valkyrie0.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/astroid0.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/clouds0.jpg")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/cloud0.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/cloud1.png")).getImage() );
              listImage.add( new ImageIcon(this.getClass().getResource("data/cloud2.png")).getImage() );
              MediaTracker mt = new MediaTracker(this);
              for(int i=0; i<listImage.size(); i++){
                   mt.addImage(listImage.get(i),0);
              try{
                   mt.waitForAll();
              catch(Exception ex){
                   ex.printStackTrace();
         public void update(Graphics g){
              this.paint(g);
         public static void main(String args[]){
              JFrame j = new JFrame();
              j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              j.setSize(1200,700);
              j.setLocationRelativeTo(null);
              main m = new main();
              m.loadImages();
              RobotValkyrieAttack r = new RobotValkyrieAttack(listImage);
              j.add(r);
              Thread t = new Thread(r);
              t.start();
              j.addKeyListener(r);
              main m = new main();
              m.init();
              j.add(m);
              j.setVisible(true);
    }

    Before we begin, note that performance of Java graphics has always been a bit 'hit and miss' in the sense that the same box with the same hardware and Java version can show radically different FPS rates if the video driver is updated.
    For better help sooner, post an SSCCE.
    Applet SSCCEs that involve images are a problem. Normally I would invite creators of image based SSCCEs to hot-link to [images available off my site|http://pscode.org/media/#image], but an applet cannot hot-link to images. It will be necessary to generate the images in code, if you want much chance of people running the code. Note that very few people will follow a link to anywhere, or download any 'build zip' or similar, to help out on a problem.
    That code snippet as posted, had a number of things that seemed horrific.
    - A class called 'main'. O_o Better would be AppletRenderTest which is not only more descriptive, but also uses the common nomenclature for a class name.
    - Frame size 1200x700?! It pays to ensure any 'comparison' of applet and application is done at the same size and my screen size is 1024x768. Make it a lot smaller, like 800x600.
    - A Swing based Timer is more typically used for Swing animation, than a Thread/Runnable.
    - GUI construction should be done on the EDT.
    - This..
    //no JApplet constructor is allowed to be overrriden..is not only factually wrong, but also incorrectly spelt.
    I am not confident you are up to writing:
    - Test code (especially test code you intend others to help with)
    - GUIs
    - Animation code
    - Applets
    Or if you are capable of parts of that, of combining the 4.
    Are you confident?

  • JApplet - maintaining state?

    Dear users,
    I'm am developing a JApplet with two JPanels on it. One of the panels has buttons and a textarea on it, and the other one is where i do some painting. It works wonderfully on my local machine. However, i have some problems when deploying it on a web server.
    As this applet reads certain files on the server before getting started, i had signed the applet properly and have uploaded it. It does not throw any exceptions and loads properly, meaning that it is able to read the files it wants. But while painting, i check if one of the hashtables has atleast one record in it. if it has, painting will proceed. if it doesnt, an error string will be painted on the JPanel. And now, my problem is, even with correct input (which is likely to put a couple of entries in the hashtable), my applet shows the error string.
    while debugging, i tried to populate the textarea with the contents of one of the files i'm trying to read. and this does not happen either. no exceptions are thrown. i'm lost.
    please have a look at this to know what i'm talking about
    http://www.mrc-lmb.cam.ac.uk/genomes/pkota/ncit/SliceIt.html
    my misery doesnt end here. when i scroll down the page, even the error string that is getting painted, disappears. how do i block that call to repaint() and maintain the so-called "state" ?
    any help is greatly appreciated.
    kota.

    getCodeBase() returns only the URL where the applet classes are located. But how do you download the data files ? With Applet.getImage() or HttpURLConnection ?
    If the applet works locally I recommend to put some debug messages (with System.out.println() ) in your code and activate the Java console for the Java plugin to find the problem.

  • Problem Loading an Image with javax Swing from a JApplet

    First of all, i use JCreator as java creater and have the newest version of java sdk version.
    Now i need to load an image from the harddrive on which the JApplet is located. I need to do this from inside the JApplet. I have put my pictures in a map 'images' which is located in the same directory as the classes + htm file. It works from inside JCreator, but as soon as i open the normal htm it just WON'T load that image (grmbl).
    Here is my code for loading the image:
    public BufferedImage loadImage (String filename, int transparency)
         Image image;
         if (app)
              image = Toolkit.getDefaultToolkit().getImage(("./images/"+filename));
         else
              String location = "";
              location = "./images/"+filename;
              image = Toolkit.getDefaultToolkit().getImage(location);
         MediaTracker mediaTracker = new MediaTracker(new Container());
         mediaTracker.addImage(image, 0);
         try
              mediaTracker.waitForID(0);
         catch (Exception e)
    Could anybody help me out here??
    I tried a url already using getCodeBase() or getDocumentBase() but that gives an error because it cannot find those if using a JApplet.

    Why don't you use javax.swing.ImageIcon? If you already have a flag telling if it's an application or applet, use the getDocumentBase() to base the URL in the applet part only.

  • Cant get image to load in JApplet - java.security.AccessControlException

    hi,
    I need to make a JApplet that loads and displays images. Before I worry about media tracker or anything else I need to get the image to load.
    My code is:
    package Applet;
    import java.awt.*; 
    import javax.swing.*;
    import java.applet.*;
    * @author Nick
    public class TestJApplet extends JApplet {
        /** Creates a new instance of TestJApplet */
        public TestJApplet() {
        public void init()
        public void paint(Graphics g)
            Image image;
            image = getImage(this.getDocumentBase(),"a.gif");
            g.drawRect(30,30,30,30);
    }where a.gif is located in the same folder as the .java file.
    I get the following message:
    Exception in thread "AWT-EventQueue-1" java.security.AccessControlException: access denied (java.io.FilePermission \C:\Documents and Settings\Nick\Math\build\a.gif read)
            at java.security.AccessControlContext.checkPermission(AccessControlContext.java:264)
            at java.security.AccessController.checkPermission(AccessController.java:427)
            at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
            at java.lang.SecurityManager.checkRead(SecurityManager.java:871)
            at sun.awt.image.URLImageSource.<init>(URLImageSource.java:37)
            at sun.applet.AppletImageRef.reconstitute(AppletImageRef.java:33)
            at sun.misc.Ref.get(Ref.java:47)
            at sun.applet.AppletViewer.getCachedImage(AppletViewer.java:377)
            at sun.applet.AppletViewer.getImage(AppletViewer.java:372)
            at java.applet.Applet.getImage(Applet.java:236)
            at java.applet.Applet.getImage(Applet.java:258)
            at Applet.TestJApplet.paint(TestJApplet.java:27)
            at sun.awt.RepaintArea.paintComponent(RepaintArea.java:248)
            at sun.awt.RepaintArea.paint(RepaintArea.java:224)
            at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:254)
            at java.awt.Component.dispatchEventImpl(Component.java:4031)
            at java.awt.Container.dispatchEventImpl(Container.java:2024)
            at java.awt.Component.dispatchEvent(Component.java:3803)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    Exception in thread "AWT-EventQueue-1" java.security.AccessControlException: access denied (java.io.FilePermission \C:\Documents and Settings\Nick\Math\build\a.gif read)
            at java.security.AccessControlContext.checkPermission(AccessControlContext.java:264)
            at java.security.AccessController.checkPermission(AccessController.java:427)
            at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
            at java.lang.SecurityManager.checkRead(SecurityManager.java:871)
            at sun.awt.image.URLImageSource.<init>(URLImageSource.java:37)
            at sun.applet.AppletImageRef.reconstitute(AppletImageRef.java:33)
            at sun.misc.Ref.get(Ref.java:47)
            at sun.applet.AppletViewer.getCachedImage(AppletViewer.java:377)
            at sun.applet.AppletViewer.getImage(AppletViewer.java:372)
            at java.applet.Applet.getImage(Applet.java:236)
            at java.applet.Applet.getImage(Applet.java:258)
            at Applet.TestJApplet.paint(TestJApplet.java:27)
            at sun.awt.RepaintArea.paintComponent(RepaintArea.java:248)
            at sun.awt.RepaintArea.paint(RepaintArea.java:224)
            at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:254)
            at java.awt.Component.dispatchEventImpl(Component.java:4031)
            at java.awt.Container.dispatchEventImpl(Container.java:2024)
            at java.awt.Component.dispatchEvent(Component.java:3803)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
            at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)Could someone help me get an image to load in an Applet/JApplet.
    Cheers :)

    From looking at your code there are two problems... the first is that you have a security exception being thrown because you are attempting to load a file locally with insufficient privileges to do so. This is because Applets have additional security levied on them so they don't say, in this circumstance steal a file off the loaded machine and send it back to the server that delivered them.
    If you want to get your applet to load a local file (I don't think that is what you're asking here) then you have to digitally sign your applet and allow the user to decide if they want to be allow it to load a local file.
    Nutshell is that you need to understand that the URL returned from getDocumentBase() in an applet is going to be from the Jar file you send the applet with or the URL you served the applet from. This is a bit of debugging code to show you what you are looking at and hopefully explain anything ambiguous I may have stated.
    package testapplication;
    import java.awt.EventQueue;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    * Description : <p></p>
    * @author John Michael Resler<br/>
    * Class : DocBaseApplet<br/>
    * Creation Time : 8:31 AM<br/>
    * Creation Date : June 18, 2006<br/>
    * Compiler : Sun Java Community Edition (version 1.5.0_06)<br/>
    public class DocBaseApplet extends javax.swing.JApplet implements MouseListener {
         * Initializes the applet DocBaseApplet
        public void init() {
            try {
                EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        initComponents();
            } catch (Exception ex) {
                ex.printStackTrace();
        private void initComponents() {
            documentBaseLabel = new javax.swing.JLabel();
            documentBaseLabel.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    documentBaseLabelMouseClicked(evt);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(documentBaseLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(documentBaseLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE)
                    .addContainerGap())
        private void documentBaseLabelMouseClicked(java.awt.event.MouseEvent evt) {                                              
            // TODO add your handling code here:
            this.documentBaseLabel.setText(this.getDocumentBase().toString());
        public void mouseClicked(MouseEvent e) {
        public void mousePressed(MouseEvent e) {
        public void mouseReleased(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
        private javax.swing.JLabel documentBaseLabel;
    }

  • 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)));

  • I have got Japplet class i try to run it as application

    i have got Japplet Class Which works fine with appletviwer and browser
    but when i try to run as an aplication it give me these error
    ican't call getCodeBase() on an application - it doesn't have an AppletContext But what else can i use instead of that:
    My code
    public class ChessPlayer extends JApplet{
    mycanvas board;
    init(){
    // this refer to gif image which have been drawn in Canvas
    board = new board (this)
    public static void main(String[] args) {
    ChessPlayer applet = new ChessPlayer();
    JFrame frame = new JFrame("Chess Game");
    //#frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent e) {
    System.exit(0);
    frame.getContentPane().add(applet);
    frame.setSize(500, 200);
    applet.init();
    applet.start();
    frame.setVisible(true);
    class Board extends Canvas
    {controler = new MediaTracker (useapplet);
    pieces [1] = useapplet.getImage (useapplet.getDocumentBase() , "images/Flower
    thank u in advance

    Just use;-
    ImageIcon icon = new ImageIcon("ChessPieceImage.jpg");
    // with all images in the same folder

  • GetCodeBase nullPointerException in JApplet called from Japplet

    When from AppletViewer I execute the following simply program, the runtime tells me:
    java.lang.NullPointerException
    at java.applet.Applet.getCodeBase(Applet.java:136)
    at ProvaLag_mlr.start(Mario.java:49)
    at Mario.start(Mario.java:25)
    at sun.applet.AppletPanel.run(AppletPanel.java:355)
    at java.lang.Thread.run(Thread.java:536)
    WHY?
    Thanks
    Mario
    Source:
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    public class Mario extends JApplet {
    JFrame WinElenco;
    public Mario() {
    public void init() {
    public void start() {
    WinElenco = new JFrame("Elenco Fumetti");
    WinElenco.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) ;
    Image vaffalovo = getImage(getCodeBase(), "1.jpg");
    ProvaLag_mlr pluto = new ProvaLag_mlr();
    WinElenco.getContentPane().add(pluto);
    WinElenco.setVisible(true);
    WinElenco.setSize(100, 100) ;
    pluto.start();
    public void stop() {
    public void run() {
    public void paint(Graphics g) {
    public void update(Graphics g) {
    paint(g);
    class ProvaLag_mlr extends JApplet implements Runnable {
    Image WorkImg;
    public void init() {
    public void start() {
    WorkImg = getImage(getCodeBase(), "1.jpg");
    public void run() {

    Like I said, you're not creating the object correctly, so when you call methods such as getCodeBase() on that object, you're likely to have those kinds of errors. It probably shouldn't be a JApplet. If you need to get the code base of your real applet (the other class), then call a method on it instead of making your second class another JApplet and trying to call a method on it.

Maybe you are looking for

  • Control break events

    Hi sdn, i have a problem when i grouping the materials under the same invoice. EX: date   address  invoice  material     1         apple                                     tomato                                     banana      2         apple       

  • Mini won't boot - tried many methods, disk visible in Target Disk Mode

    I have a PPC Mac Mini running Leopard. It stopped booting last week. It goes to the point where the Apple appears and then stops. No moving ring at the bottom of the screen. I've done the following w/ no luck to get it booting. 1) Put it in Target Di

  • Boot camp error installing Windows 8.1 "An unexpected I/O error has occurred"

    Well, just like it says on the title, when im going to install windows 8.1 in my MBP (late 2011 13" i7) it gives me a blue screen and the message "RECOVERY There was a problem with a device connected to your PC An unexpected I/O error has occurred Er

  • HTTP Receiver interface returns with error code 110

    Hi All, We are posting the document from XI to a external server as HTTPS request. We are able to sucessfully post the request to external server using HTTP destination as address type but not able to post sucessfully with URL as address type. Here g

  • SCCM 2012: Assigned updates to update group don't get there deployment

    Hello, Problem: When I assign available updates to the update group the updates are not getting there deployment. Deployed: NO (Previous months no problem) Situation: SCCM 2012 SP1 We made different Update groups. Example: Windows 2008 R2 This group