Applet repaint

I have a problem when i resize the browser window. The part of the applet which used to be covered is left with ruined graphic.
How do I solve this problem?

In your html, capture the 'onresize' event of the browser. In onresize, you can use the capability that javascript can communicate with an applet. Call the repaint method of your applet from javascript trigger by onresize.
Check out this link:
http://java.sun.com/products/plugin/1.3/docs/jsobject.html

Similar Messages

  • Applet repainting error in IE 5.5 using the scrollbars

    I've created a real straight forward applet using swing components to test out this error. It consists of a couple of JButtons & JLabels added to a JPanel that's the JPanel is added to the ContentPane. I'm using the Java Plug-in 1.3 on a Windows 2000 box using IE 5.5. When I view my applet everything is just fine. But when I'm using the browser scrollbars to view the rest of my applet and try to scroll down, the applet controls and everything within the applet does not get repainted properly onto the screen. Everything in the applet gets painted on top of their old controls a couple of pixels off making it impossible to use. When I scroll to the bottom and top of the page the applet repaints just fine, but it's when I'm scrolling in the middle of the page is where the applet can not repaint properly. I have tested this in Netscape 6.0 and everything works just fine. I'mnot sure what could be causing this but maybe one of you have cameacross this problem before and could help out.
    thanks,
    Peter Landis.

    Here's the code:
    import java.awt.*;
    import javax.swing.*;
    public class TestRepaint extends JApplet
    public void init()
         Container contentPane = getContentPane();
         JPanel panel = new JPanel();
    panel.setBackground(Color.lightGray);
    controls(panel);
         // Grid
         contentPane.add(panel);
    public void controls(JPanel p)
    JLabel imagelabel = new JLabel();
    JLabel imagelabel2 = new JLabel();
    // Create some labels
    JLabel label_1 = new JLabel("TEST 1");
    JLabel label_2 = new JLabel("TEST 2");
    JLabel label_3 = new JLabel("TEST 3");
    JLabel label_4 = new JLabel("TEST 4");
    JLabel label_5 = new JLabel("TEST 5");
    JLabel label_6 = new JLabel("TEST 6");
    JLabel label_7 = new JLabel("TEST 7");
    setLabelControl(label_1);
    setLabelControl(label_2);
    setLabelControl(label_3);
    setLabelControl(label_4);
    setLabelControl(label_5);
    setLabelControl(label_6);
    setLabelControl(label_7);
    // Buttons
    JButton b1 = new JButton("Button 1");
    JButton b2 = new JButton("Button 2");
    JButton b3 = new JButton("Button 3");
    JButton b4 = new JButton("Button 4");
    JButton b5 = new JButton("Button 5");
    JButton b6 = new JButton("Button 6");
    JButton b7 = new JButton("Button 7");
    setButtonControl(b1);
    setButtonControl(b2);
    setButtonControl(b3);
    setButtonControl(b4);
    setButtonControl(b5);
    setButtonControl(b6);
    setButtonControl(b7);
    // Layout
         GridBagLayout gridbag = new GridBagLayout();
         GridBagConstraints c = new GridBagConstraints();
    p.setLayout(gridbag);
    c.anchor = GridBagConstraints.WEST;
         c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.gridwidth = 1;
    // Note Inset is (Top, Left, Bottom, Right);
    c.insets = new Insets(0,5,20,0);
         p.add(label_3,c);
         c.insets = new Insets(0,5,20,1);
    p.add(b3,c);
    c.insets = new Insets(0,5,20,0);
         p.add(label_4,c);
    c.gridwidth = GridBagConstraints.REMAINDER;
         c.insets = new Insets(0,5,20,1);
    p.add(b4,c);
    c.gridwidth = 1;
    c.insets = new Insets(0,5,20,0);
         p.add(label_5,c);
         c.insets = new Insets(0,5,20,1);
    p.add(b5,c);
    c.insets = new Insets(0,5,20,0);
         p.add(label_6,c);
    c.gridwidth = GridBagConstraints.REMAINDER;
         c.insets = new Insets(0,5,20,1);
    p.add(b6,c);
    public void setButtonControl(JButton button)
              button.setBackground(Color.white);
    void setLabelControl(JLabel l)
              l.setFont(new Font("Helvetica", Font.BOLD, 14) );
    l.setForeground(Color.black);
    ||||||||||||||||||||| HTML CODE |||||||||||||||||||
    <title>Test</title>
    <hr>
    <!--"CONVERTED_APPLET"-->
    <!-- CONVERTER VERSION 1.3 -->
    <SCRIPT LANGUAGE="JavaScript"><!--
    var info = navigator.userAgent; var ns = false;
    var ie = (info.indexOf("MSIE") > 0 && info.indexOf("Win") > 0 && info.indexOf("Windows 3.1") < 0);
    //--></SCRIPT>
    <COMMENT><SCRIPT LANGUAGE="JavaScript1.1"><!--
    var ns = (navigator.appName.indexOf("Netscape") >= 0 && ((info.indexOf("Win") > 0 && info.indexOf("Win16") < 0 && java.lang.System.getProperty("os.version").indexOf("3.5") < 0) || (info.indexOf("Sun") > 0) || (_info.indexOf("Linux") > 0)));
    //--></SCRIPT></COMMENT>
    <SCRIPT LANGUAGE="JavaScript"><!--
    if (_ie == true) document.writeln('<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" WIDTH = 500 HEIGHT = 425 codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,0,0"><NOEMBED><XMP>');
    else if (_ns == true) document.writeln('<EMBED type="application/x-java-applet;version=1.3" CODE = "TestRepaint.class" WIDTH = 500 HEIGHT = 425 scriptable=false pluginspage="http://java.sun.com/products/plugin/1.3/plugin-install.html"><NOEMBED><XMP>');
    //--></SCRIPT>
    <APPLET CODE = "TestRepaint.class" WIDTH = 500 HEIGHT = 425></XMP>
    <PARAM NAME = CODE VALUE = "TestRepaint.class" >
    <PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">
    <PARAM NAME="scriptable" VALUE="false">
    </APPLET>
    </NOEMBED></EMBED></OBJECT>
    <!--
    <APPLET CODE = "TestRepaint.class" WIDTH = 500 HEIGHT = 425>
    </APPLET>
    -->
    <!--"END_CONVERTED_APPLET"-->
    <hr>

  • Swing Applet Repainting during moving window

    Hi,
    I've run into a problem with my swing JApplet. One of the elements of my GUI is a JLabel that contains a single Image. After the GUI is created, a seperate thread changes the image and prompts the JPanel containing the JLabel to repaint().
    Now, this works perfectly with the AppletViewer using java 1.4.2.03. However, when I run the applet through Microsoft's Internet Explorer using Sun's VM 1.4.2.03 plugin, I notice a problem. If I take the window containing the applet and (assuming it is NOT maximized) move it around the screen, the JLabel's image will not always be drawn at the correct place. It will often overlap some of the other GUI elements.
    I read something that Threads and Applets don't mix which suggested using the SwingUtilities.invokeLater() function, but I need this Thread to sleep() and didn't know how to make it do so because I never see the Thread class through the invokeLater() method.
    It solves the problem if rather than have the JLabel repaint itself, I have the entire applet repaint itself, but this is not the ideal solution. Is there any way to determine when the window containing the applet is being moved and then force the applet to repaint itself entirely? Am I going about this wrong? Any help would be greatly appreciated!
    Thanks,
    B. Danny K.

    The content pane of a JApplet is a JPanel. So you need to use the getContentPane() method and cast the Compnent to a JPanel before you can use revalidate(). However, as you have discovered 99% of the time a validate() also works.
    Note, that is you are using a BorderLayout then you should be removing the old component before adding the new component.

  • Applet: repaint() causing infinite loop

    I'm developing an applet that draws a linegraph. The user can select which lines of points will be drawn in the applet using checkboxes. I have a separate function as an Itemlistener for the checkboxes, and I call repaint at the end of the itemStateChanged function. For some reason, once the itemlistener has seen one event, the applet gets stuck in a loop, and paint is continually run over and over again. This makes the applet useless as the user can't enter any input since the applet is continually being redrawn. I only want paint to be called once from a repaint() call. I'm not using any loops anywere in my program. Any suggestions?

    ItemListeners tend to throw lots of events when actually only one has happened.
    The solution i use:
    remember the old satus. when an event happens first check if the status has changed, if not do nothing.

  • Safari doesn't call applet repaint.

    When Safari becomes the top application, after being under another window, it does not call a Java Applet's repaint.
    When playing Runescape (www.runescape.com) this means you have to log into the game again. Firefox does not have this problem.

    You forgot to add the mouseListener
    In the constructor, aftet this line System.out.println("CpaintRect");
         addMouseListener(this);
    Noah

  • Applet repaint problem

    Hi
    I have problem with repainting. I add components to panel, then in action listener remove them and add a different component. After that the panel is empty, but when I resize the applet, the component appears.
    Do you have any ideas what's wrong?
    Here is the code:
    public class test extends JApplet{
         private Container aplet;                                   
              private JPanel
                   podspodnik = new JPanel(new BorderLayout());
              private JTextPane
                   wyswietl = new JTextPane();          
              private JButton
                   wywolaj = new JButton("Wywolaj"),
                   but = new JButton("Juppi!");
              public void init()
                   try
                        javax.swing.SwingUtilities.invokeAndWait(new Runnable()
                        public void run()
                             createAndShowGUI();
                   catch (Exception noGUI)
                        System.err.println("Nie udalo sie utworzyc interfejsu!!");
                        JOptionPane.showMessageDialog(null,
                                       "Nie udalo sie utworzyc interfejsu!!!",
                                       "Blad krytyczny okna",
                                       JOptionPane.ERROR_MESSAGE);
              private void createAndShowGUI(){
                   aplet = getContentPane();
                   aplet.setPreferredSize(new Dimension(300, 300));
                   wyswietl.setPreferredSize(new Dimension(200, 300));
                   wyswietl.setPreferredSize(new Dimension(130,20));
                   wywolaj.setPreferredSize(new Dimension(130, 20));
                   podspodnik.add(wyswietl, BorderLayout.NORTH);
                   podspodnik.add(wywolaj, BorderLayout.CENTER);
                   aplet.add(podspodnik);
                   addListeners();
                   aplet.setVisible(true);
                   aplet.repaint();
              private void addListeners(){
                   wywolaj.addActionListener(new ActionListener()
                                  public void actionPerformed(ActionEvent e)
                                       podspodnik.remove(wyswietl);
                                       podspodnik.remove(wywolaj);
                                       podspodnik.add(but, BorderLayout.CENTER);
                                       aplet.repaint();
    }

    Try to post this problem in the Java Applet Development forum instead.(
    http://forum.java.sun.com/forum.jspa?forumID=421).
    Applet != Servlet

  • ERROR in my applet program

    When I execute my applet, it gives me this error:
    Exception in thread "main" java.lang.NoSuchMethodError: main
    However when it runs in the appletviewer fine. Heres the code:
    import java.applet.Applet;
    import java.awt.*;
    import javax.swing.*;
    public class slideshow extends Applet implements Runnable
            //creates the main thread
         Thread mainthread=null;
         //the amount of sleep time for the thread
         int time=2000; //milliseconds
            int x=1;
            int numberofimages=5; //this variable is needed since the paint function will know how many
            private Image bgimage1;
            private Image bgimage2;
            private Image bgimage3;
            private Image bgimage4;
            private Image bgimage5;
            String parameter;
         public void init()
                    parameter = getParameter("totalimages");
                    int numimages = (parameter==null? 0:Integer.parseInt(parameter));
                    numberofimages=numimages;//setting the global to this value
                    String imagename = getParameter( "name" );
                    String imagename2 = getParameter( "name2" );
                    String imagename3 = getParameter( "name3" );
                    String imagename4 = getParameter( "name4" );
                    String imagename5 = getParameter( "name5" );
                    bgimage1=getImage(getDocumentBase(), imagename);
                    bgimage2=getImage(getDocumentBase(), imagename2);
                    bgimage3=getImage(getDocumentBase(), imagename3);
                    bgimage4=getImage(getDocumentBase(), imagename4);
                    bgimage5=getImage(getDocumentBase(), imagename5);
              //constructs the thread
              mainthread=new Thread(this);
              //starts the thread
              mainthread.start();
        public void run(){
              while(mainthread!=null)
                    {try{
                  //makes the thread sleep
                  mainthread.sleep(time);
              catch(Exception e){}
              //repaints the applet
              repaint();
        public void stop()
              if(mainthread!=null){mainthread.stop();}
        public void paint(Graphics g)
                if (x==1)
                   g.drawImage(bgimage1,0,0,getWidth(),getHeight(),this);
                   //draws image the full size of the applet
                if (x==2)
                   g.drawImage(bgimage2,0,0,getWidth(),getHeight(),this);
                if (x==3)
                   g.drawImage(bgimage3,0,0,getWidth(),getHeight(),this);
                if (x==4)
                   g.drawImage(bgimage4,0,0,getWidth(),getHeight(),this);
                if (x==5)
                   g.drawImage(bgimage5,0,0,getWidth(),getHeight(),this);           
                x++;
                if (x>numberofimages)
                   x=1; 
    //end     
    }     

    When you say "execute" do you mean you are trying to launch your Applet as an application like:
    java slideshow
    That won't work because your code is only an Applet. When you invoke a class with the java.exe command, you need a main method and your code doesn't have one. You'll also need to explicitly call init() and run(), and you'll need to provide a Frame to hold your Applet.

  • Painting in applets

    I ran into a problem using AWT in applets. Sometimes in IE the animated applets repaints in a random place. Sometimes it's taskbar area, sometimes browsers toolbar. I don't know if it's JRE 1.3.1_08's bug or it may be code's fault.
    Anyone ran into similar issue?

    Thanx Foxy Lady ;), but he problem occurs more often in an applet like this. Simple ticker with double buffering. I think the problem is in refreshing the applet more often than one second. Here's the code:
    import java.applet.Applet;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Color;
    import java.awt.FontMetrics;
    import java.awt.Image;
    public class Ticker extends Applet implements Runnable {
         * Whole text to draw.
        String text = new String();
         * Single line from the script.
        String line;
         * Speed of moving text.
        int delay;
         * Background color.
        int bgColor;
         * Foreground color.
        int color;
         * Flag indicating if this applet is still active.
        boolean flag = true;
        int i = 0;
         * Offscreen image for doublebuffering.
        Image offscreenImage;
         * Width of the whole text.
        int textWidth;
         * Width of the applet.
        int wdth;
         *  The initialization method - getting parameters from the script.
        public void init() {
            line = new String(getParameter("text"));
            bgColor = Integer.parseInt(getParameter("bgColor"), 16);
            color = Integer.parseInt(getParameter("color"), 16);
            delay = Integer.parseInt(getParameter("delay"));
            wdth = Integer.parseInt(getParameter("width"));
            setBackground(new Color(bgColor));
            setSize(wdth, 20);
            offscreenImage = createImage(wdth, 20);
        public void paint(Graphics g) {
            drawText(i, g);
         * Draws the text in the <code>iks</code> position.
         * @param iks position of the text.
         * @param gr graphics context.
        public void drawText(int iks, Graphics gr) {
            gr.setColor(new Color(color));
            gr.setFont(new Font("SansSerif", Font.BOLD, 15));
            if (iks < -(textWidth - wdth)) {
                //if the whole text went away to the left
                //we should draw it from the beginning
                gr.drawString(text, iks + textWidth, 15);
            gr.drawString(text, iks, 15);
        public void update(Graphics g) {
            //getting the offscreen graphics context
            Graphics offscreenG = offscreenImage.getGraphics();
            //clearing the offscreen
            offscreenG.clearRect(0, 0, wdth, 20);
            //drawing the text in the offscreen
            paint(offscreenG);
            //replacing the screen with a ready offscreen image
            g.drawImage(offscreenImage, 0, 0, this);
        public void run() {
            Graphics g = getGraphics();
            FontMetrics metrics;
            //preparing the text to show
            g.setFont(new Font("SansSerif", Font.BOLD, 15));
            metrics = g.getFontMetrics();
            textWidth = metrics.stringWidth(text);
            while (textWidth <= wdth) {
                //if the text is shorter than the applet width
                //we shoul repeat it after a "+" sign.
                text += "+" + line;
                textWidth = metrics.stringWidth(text);
            text = text + "+";
            text = "++" + text;
            textWidth = metrics.stringWidth(text);
            //repainting the applet
            while (flag) {
                if (i < -textWidth) i = 0;
                i--;
                repaint();
                try {
                    Thread.sleep(delay * 20);
                } catch (InterruptedException e) {
         * Start the thread.
        public void start() {
            new Thread(this).start();
         * Stop the thread.
        public void stop() {
            flag = false;
        public void destroy() {
    }

  • Some two threaded image prepare and painting applet coordination problem

    hi all,
    i'm sure this multithreaded gui is complex but anyway. a simple producer&consumer type applet. there is one seperate thread preparing an offscreen image, and the main guy draws it on applet. i can not coordinate them, what's wrong i don't know. simply, applet starts a thread, which paints something on an offscreen image, and then tells to applet repaint(). anyway, here is the code, this small png files are a lot, idea is making a view on them, just imagine a big big png file divided into matrices. afterall this is not the important part. what i see on the screen is, if you ask, nothing.
    thanx,
    ozz
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.lang.reflect.Array;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class MapViewer
         extends JFrame
         Image map[][];
         public MapViewer()
              int dimensions[] = { 58, 46 };
              map = (Image[][]) Array.newInstance(Image.class, dimensions);
              try
                   loadImages();
              catch(Exception e)
                   e.printStackTrace();
         public void loadImages()
              throws Exception
              for(int i=0; i<58; i++)
                   for(int j=0; j<46; j++)
                        StringBuffer sb = new StringBuffer();
                        sb.append("C:\\map\\");
                        sb.append(i+1);
                        sb.append("_");
                        sb.append(46-j);
                        sb.append(".png");
                        map[i][j] = Toolkit.getDefaultToolkit().getImage( sb.toString() );
         public void go()
              initComponents();
              show();
         private void initComponents()
              addWindowListener
                   new java.awt.event.WindowAdapter()
                        public void windowClosing(java.awt.event.WindowEvent evt)
                             exitForm(evt);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new MapPanel(), BorderLayout.NORTH);
              pack();
         private void exitForm(java.awt.event.WindowEvent evt)
              System.exit(0);
         public static void main(String args[])
              new MapViewer().go();
         private class MapPanel
              extends JPanel
              implements MouseMotionListener, Runnable
              private int north = 1;
              private int east = 2;
              private int south = 4;
              private int west = 8;
              private int direction;
              private Image model;
              private Boolean refreshModel = Boolean.TRUE;
              private Boolean modelReady = Boolean.FALSE;
              private Point start = new Point(200, 200);
              public MapPanel()
                   addMouseMotionListener(this);
                   new Thread(this).start();
              public synchronized Image requestImage()
                   return createImage(1600, 1600);
              public Dimension getMinimumSize()
                   return new Dimension(400, 400);
              public Dimension getPreferredSize()
                   return new Dimension(400, 400);
              public void paint(Graphics g)
                   synchronized(modelReady)
                        if(modelReady.booleanValue() == true)
                             g.drawImage(model, 0, 0, null);
                   g.setColor(Color.white);
                   g.fillRect(0, 0, 30, 10);
                   g.setColor(Color.black);
                   g.drawString(String.valueOf(direction), 0, 10);
              public void mouseDragged(MouseEvent e)
              public void mouseMoved(MouseEvent e)
                   Point p = e.getPoint();
                   findDirection(p);
              private void findDirection(Point p)
                   direction = 0;
                   if(p.x < 100)
                        direction |= west;
                   else if(p.x > 300)
                        direction |= east;
                   if(p.y < 100)
                        direction |= north;
                   else if(p.y > 300)
                        direction |= south;
              public void moveIt()
                   int px = 20;
                   int py = 20;
                   synchronized(refreshModel)
                        if(refreshModel.booleanValue() == true)
                             model = requestImage();
                             if(model == null || model.getGraphics() == null)
                                  return;
                             Graphics g = model.getGraphics();
                             for(int x=0; x < 4; x++)
                                  for(int y=0; y<4; y++)
                                       g.drawImage(map[px+x][py+y], x*200, y*200, null);
                             refreshModel = Boolean.FALSE;
                             modelReady = Boolean.TRUE;
    //               start.x -= 3;
    //               start.y -= 3;
              public void run()
                   while(true)
                        try
                             moveIt();
                             repaint();
                             Thread.currentThread().sleep(20);
                        catch(InterruptedException ie)

    Hi.
    The Graphics.drawImage method is asynchronyous, that may be the reason of the problem. Set an ImageObserver parameter in drawImage method, when drawing on an offscreen image. Count finished images and when all are done
    draw the big image on the screen.
    Alternatively you can call Toolkit.prepareImage method in a loop, after loadimages and wait until all images are loaded(true returned).

  • Applet causes GDI Leak using 1.5.0_06 only

    Hi,
    Since the release of 1.5.0_06 our applet has developed a GDI Object leak. Basically, our applet draws on a panel when ever an update is available. The previous versions of the JVM seem fine and th e GDI Objects are stable, but this new version eats the GDIs up really quickly, and never releases them.
    The problem occurs when the applet repaints itself. Calling repaint() or paint() from code works ok with no leaks but as soon as the applet is forced to repaint because of a resize, or because another window has moved over it the GDIs go up by multiples of 10.
    Here is some sample code:
    import java.awt.*;
    import java.applet.*;
    import java.util.Date;
    public class GDIApplet extends Applet {
        //Construct the applet
        public GDIApplet() {
        //Initialize the applet
        public void init() {
            try {
                jbInit();
            } catch (Exception e) {
                e.printStackTrace();
        //Component initialization
         private void jbInit() throws Exception {
             this.setLayout(new BorderLayout());
             this.add(new GDIPanel(), BorderLayout.CENTER);
         public class GDIPanel extends Panel implements Runnable{
        public GDIPanel() {
            Thread t = new Thread(this,"SPGPaintTimer");
            t.start();
        public void paint(Graphics g){
            if( g == null){
                return;
            System.out.println("Paint on thread: " + Thread.currentThread().getName());
            Date d = new Date();
            Rectangle bounds = getBounds();
            g.setColor(Color.black);
            g.fillRect(0,0, bounds.width, bounds.height);
            FontMetrics fm = g.getFontMetrics();
            String val = d.toString();
            int width = fm.stringWidth(val);
            int height = fm.getHeight();
            int x = (bounds.width - width) /2;
            int y = (bounds.height/2) - height;
            g.setColor(Color.yellow);
            g.drawString(val,x,y);
        public void run(){
            while(true){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                repaint();
    }

    could you please file a bug-repor at bugs.sun.com - this would ensure that java-developers are looking into this issue.
    lg Clemens

  • Applet using JVM 1.5.0_06 causes GDI Object Leaks

    Hi,
    Since the release of 1.5.0_06 our applet has developed a GDI Object leak. Basically, our applet draws on a panel when ever an update is available. The previous versions of the JVM seem fine and th e GDI Objects are stable, but this new version eats the GDIs up really quickly, and never releases them.
    The problem occurs when the applet repaints itself. Calling repaint() or paint() from code works ok with no leaks but as soon as the applet is forced to repaint because of a resize, or because another window has moved over it the GDIs go up by multiples of 10.
    Here is some sample code:
    import java.awt.*;
    import java.applet.*;
    import java.util.Date;
    * <p>Copyright: Copyright (c) 2005</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class GDIApplet extends Applet {
        //Construct the applet
        public GDIApplet() {
        //Initialize the applet
        public void init() {
            try {
                jbInit();
            } catch (Exception e) {
                e.printStackTrace();
        //Component initialization
         private void jbInit() throws Exception {
             this.setLayout(new BorderLayout());
             this.add(new GDIPanel(), BorderLayout.CENTER);
         public class GDIPanel extends Panel implements Runnable{
        public GDIPanel() {
            Thread t = new Thread(this,"SPGPaintTimer");
            t.start();
        public void paint(Graphics g){
            if( g == null){
                return;
            System.out.println("Paint on thread: " + Thread.currentThread().getName());
            Date d = new Date();
            Rectangle bounds = getBounds();
            g.setColor(Color.black);
            g.fillRect(0,0, bounds.width, bounds.height);
            FontMetrics fm = g.getFontMetrics();
            String val = d.toString();
            int width = fm.stringWidth(val);
            int height = fm.getHeight();
            int x = (bounds.width - width) /2;
            int y = (bounds.height/2) - height;
            g.setColor(Color.yellow);
            g.drawString(val,x,y);
        public void run(){
            while(true){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                repaint();
    }

    Hi there.
    I've found this page by googling.
    I am not a Java developer, but am using a third party java applet on my web page for mapping.
    Funnily enough, I've been trying to hunt down a memory leak thats occuring in IE (not any other browser).
    It only occurs when the applet is physically visible on the page, and the user is using the Sun JVM (1.5.0_06). The GDI object count increases every time I mouseover a link in a tree.
    This does not occur with the MS JVM.
    Unfortunately I do not have access to the applet source code, but I'm wondering if its related to your problem.
    Have you had any success on this?
    Thanks.

  • Applet works fine in NetBeans IDE,show grey lines on the web(html page)?

    Hi every body?
    Just wanted to see if someone ever came accross with this problem?
    Please HELP HELP!!!
    Problem: my applet shows some grey lines on the web wehn i move my applet quickly left or right. However they disapear if i move any other gui on top of it like eraser.
    I open the applet in an html file using simple open my applet in new window.
    I think it's not applet repaint or validate problem .. it 's the msn explorer related problem..
    Thanks for your help in advance..
    FYI: The same applet works fine on my pc using Net beans IDE .

    You mean start over from scratch ... that sounds like fun.
    java console is nice, found the problem to be
    Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied (java.io.FilePermission C:\Documents and Settings\Michael\My Documents\NetBeansProjects\BasicMath\pictures read)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkRead(Unknown Source)
         at java.io.File.list(Unknown Source)
         at java.io.File.listFiles(Unknown Source)
         at basicmath.BasicInterface.<init>(BasicInterface.java:42)
         at basicmath.MainApplet.startup(MainApplet.java:145)
         at basicmath.MainApplet.actionPerformed(MainApplet.java:125)
         at java.awt.Button.processActionEvent(Unknown Source)
         at java.awt.Button.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)Which is not a solution but at least i know what the problem is. If anyone else has this type of problem start the "java console" then go run your app, the console will print out the error (because there is one).
    sorry if im dumb.
    Edited by: ZoneMikel on May 6, 2008 6:58 PM

  • Problems with an applet

    Hi all. First time poster here. I'm struggling with an assignment I have for school and was wondering if any one could help me out. The finished applet is supposed to look like this:
    http://i652.photobucket.com/albums/uu242/cdub05/applet.png?t=1263867517
    My problem is that I can't get the three rectangles to displays. The labels, textboxes, and button show up, but the rectangles do not. If anybody can tell me what I am doing wrong, it would be greatly appreciated. Here is my code so far:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ColorApplet extends JApplet
    implements ActionListener
         private JTextField txtRed = new JTextField("255", 3);
         private JTextField txtGreen = new JTextField("255", 3);
         private JTextField txtBlue = new JTextField("255", 3);
         private JButton cmdEnter = new JButton("Enter");
         private int red=255;
         private int green=255;
         private int blue=255;
         * The entry point for the applet.
         public void init()
    // get contentPane & set layout manager
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
              // text components & labels
              cp.add(new JLabel("CPT 237 - Java - Color Class RGB Component Demonistration Applet"));
              cp.add(new JLabel("Red"));
              cp.add(txtRed);
              cp.add(new JLabel("Green"));
              cp.add(txtGreen);
              cp.add(new JLabel("Blue"));
              cp.add(txtBlue);
              // add button and set up handler
              cp.add(new colorPanel());
              cp.add(cmdEnter);
              cmdEnter.addActionListener(this);
    class colorPanel extends JPanel{
    protected void paintComponent(Graphics g)
              super.paintComponent(g);
              // draw the large rectangle
              g.setColor(new Color(red, green, blue));
              g.fillRect(100, 100, 200, 150);
              // draw the red component rectangle
              g.setColor(new Color(red, 0, 0));
              g.fillRect(120, 120, 40, 100);
              // draw the green component rectangle
              g.setColor(new Color(0, green, 0));
              g.fillRect(180, 120, 40, 100);
              // draw the blue component rectangle
              g.setColor(new Color(0, 0, blue));
              g.fillRect(240, 120, 40, 100);
         public void actionPerformed(ActionEvent e)
              // get color components
              red = Integer.parseInt(txtRed.getText());
              green = Integer.parseInt(txtGreen.getText());
              blue = Integer.parseInt(txtBlue.getText());
              // repaint the applet
              repaint();
    }

    Your colorPanel has been added to your applet, but it is very small, in fact 0 size. You may wish to give it a preferred size by calling setPreferredSize(new Dimension(...)) on it. Also, you may wish to consider reading up on and trying out some different layouts such as BorderLayout.
    Also, when posting code here, please use code tags so that your code will retain its formatting and thus will be readable -- after all, your goal is to get as many people to read your post and understand your code as possible, right?
    To do this, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.
    Another way to do this is to manually place the tags into your code by placing the tag [cod&#101;] above your pasted code and the tag [cod&#101;] below your pasted code like so:
    [cod&#101;]
      // your code goes here
      // notice how the top and bottom tags are different
    [/cod&#101;]Finally, welcome to the forum!

  • How do I fix extremely slow rendering with buffered images?

    I've found random examples of people with this problem, but I can't seem to find any solutions in my googling. So I figured I'd go to the source. Basically, I am working on a simple platform game in java (an applet) as a surprise present for my girlfriend. The mechanics work fine, and are actually really fast, but the graphics are AWFUL. I wanted to capture some oldschool flavor, so I want to render several backgrounds scrolling in paralax (the closest background scrolls faster than far backgrounds). All I did was take a buffered image and create a graphics context for it. I pass that graphics context through several functions, drawing the background, the distant paralax, the player/entities, particles, and finally close paralax.
    Only problem is it runs at like 5 fps (estimated, I havn't actually counted).
    I KNOW this is a graphics thing, because I can make it run quite smoothly by commenting out the code to draw the background/paralax backgrounds... and that code is nothing more complicated than a graphics2d.drawImage
    So obviously I am doing something wrong here... how do I speed this up?
    Code for main class follows:
    import javax.swing.JApplet;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.event.*;
    import Entities.*;
    import Worlds.*;
    // run this applet in 640x480
    public class Orkz extends JApplet implements Runnable, KeyListener
         double x_pos = 10;
         double y_pos = 400;
         int xRes=640;
         int yRes=480;
         boolean up_held;
         boolean down_held;
         boolean left_held;
         boolean right_held;
         boolean jump_held;
         Player player;
         World world;
         BufferedImage buffer;
         Graphics2D bufferG2D;
         int radius = 20;
         public void init()
              //xRes=(int) this.getSize().getWidth();
              //yRes=(int) this.getSize().getHeight();
            buffer=new BufferedImage(xRes, yRes, BufferedImage.TYPE_INT_RGB);
            bufferG2D=buffer.createGraphics();
              addKeyListener(this);
         public void start ()
                player=new Player(320, 240, xRes,yRes);
                world=new WorldOne(player, getCodeBase(), xRes, yRes);
                player.setWorld(world);
               // define a new thread
               Thread th = new Thread (this);
               // start this thread
               th.start ();
         public void keyPressed(KeyEvent e)
              //works fine
         }//end public void keypressed
         public void keyReleased(KeyEvent e)
              //this works fine
         public void keyTyped(KeyEvent e)
         public void paint( Graphics g )
               update( g );
        public void update(Graphics g)
             Graphics2D g2 = (Graphics2D)g;              
             world.render(bufferG2D);                
             g2.drawImage(buffer, null, null);
         public void run()
              // lower ThreadPriority
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              long tm;
              long tm2;
              long tm3;
              long tmAhead=0;
              // run a long while (true) this means in our case "always"
              while (true)
                   tm = System.currentTimeMillis();
                   player.moveEntity();
                  x_pos=player.getXPos();
                  y_pos=player.getYPos();
                  tm2 = System.currentTimeMillis();
                    if ((tm2-tm)<20)
                     // repaint the applet
                     repaint();
                    else
                         System.out.println("Skipped draw");
                    tm3= System.currentTimeMillis();
                    tmAhead=25-(tm3-tm);
                    try
                        if (tmAhead>0) 
                         // Stop thread for 20 milliseconds
                          Thread.sleep (tmAhead);
                          tmAhead=0;
                        else
                             System.out.println("Behind");
                    catch (InterruptedException ex)
                          System.out.println("Exception");
                    // set ThreadPriority to maximum value
                    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
         public void stop() { }
         public void destroy() { }
    }Here's the code for the first level
    package Worlds;
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.util.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.File;
    import java.net.URL;
    import java.awt.geom.AffineTransform;
    import Entities.Player;
    public class WorldOne implements World
         Player player;
         //Location of Applet
         URL codeBase;
         // Image Resources
         BufferedImage paralax1Image;
         BufferedImage paralax2Image;
         BufferedImage backgroundImage;
         // Graphics Elements     
         int xRes;
         int yRes;
         double paralaxScale1,paralaxScale2;
         double worldSize;
         int frameX=1;
         int frameY=1;
         public WorldOne(Player player, URL codeBase, int xRes, int yRes)
              this.player=player;
              this.codeBase=codeBase;
              this.xRes=xRes;
              this.yRes=yRes;
              worldSize=4000;
            String backgroundImagePath="worlds\\world1Graphics\\WorldOneBack.png";
            String paralax1ImagePath="worlds\\world1Graphics\\WorldOnePara1.png";
            String paralax2ImagePath="worlds\\world1Graphics\\WorldOnePara2.png";
            try
            URL url1 = new URL(codeBase, backgroundImagePath);
             URL url2 = new URL(codeBase, paralax1ImagePath);
             URL url3 = new URL(codeBase, paralax2ImagePath);
            backgroundImage = ImageIO.read(url1);
            paralax1Image  = ImageIO.read(url2);
            paralax2Image = ImageIO.read(url3);
            paralaxScale1=(paralax1Image.getWidth()-xRes)/worldSize;
            paralaxScale2=(paralax2Image.getWidth()-xRes)/worldSize;
            catch (Exception e)
                 System.out.println("Failed to load Background Images in Scene");
                 System.out.println("Background Image Path:"+backgroundImagePath);
                 System.out.println("Background Image Path:"+paralax1ImagePath);
                 System.out.println("Background Image Path:"+paralax2ImagePath);
         }//end constructor
         public double getWorldSize()
              double xPos=player.getXPos();
              return worldSize;
         public void setFramePos(int frameX, int frameY)
              this.frameX=frameX;
              this.frameY=frameY;
         public int getFrameXPos()
              return frameX;
         public int getFrameYPos()
              return frameY;
         public void paralax1Render(Graphics2D renderSpace)
              int scaledFrame=(int)(paralaxScale1*frameX);
              renderSpace.drawImage(paralax1Image,-scaledFrame,0,null); //Comment this to increase performance Massively
         public void paralax2Render(Graphics2D renderSpace)
              int scaledFrame=(int)(paralaxScale2*frameX);
              renderSpace.drawImage(paralax2Image,-scaledFrame,0,null); //Comment this to increase performance Massively
         public void backgroundRender(Graphics2D renderSpace)
              renderSpace.drawImage(backgroundImage,null,null); //Comment this to increase performance Massively
         public void entityRender(Graphics2D renderSpace)
              //System.out.println(frameX);
              double xPos=player.getXPos()-frameX+xRes/2;
             double yPos=player.getYPos();
             int radius=15;
             renderSpace.setColor (Color.blue);
            // paint a filled colored circle
             renderSpace.fillOval ((int)xPos - radius, (int)yPos - radius, 2 * radius, 2 * radius);
              renderSpace.setColor(Color.blue);
         public void particleRender(Graphics2D renderSpace)
              //NYI
         public void render(Graphics2D renderSpace)
              backgroundRender(renderSpace);
              paralax2Render(renderSpace);
              entityRender(renderSpace);
              paralax1Render(renderSpace);
    }//end class WorldOneI can post more of the code if people need clarification. And to emphasize, if I take off the calls to display the background images (the 3 lines where you do this are noted), it works just fine, so this is purely a graphical slowdown, not anything else.
    Edited by: CthulhuChild on Oct 27, 2008 10:04 PM

    are the parallax images translucent by any chance? The most efficient way to draw images with transparent areas is to do something like this:
         public static BufferedImage optimizeImage(BufferedImage img)
              GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();                    
              GraphicsConfiguration gc = gd.getDefaultConfiguration();
              boolean istransparent = img.getColorModel().hasAlpha();
              BufferedImage img2 = gc.createCompatibleImage(img.getWidth(), img.getHeight(), istransparent ? Transparency.BITMASK : Transparency.OPAQUE);
              Graphics2D g = img2.createGraphics();
              g.drawImage(img, 0, 0, null);
              g.dispose();
              return img2;
         }I copied this from a util class I have and I had to modify it a little, I hope I didn't break anything.
    This piece of code does a number of things:
    - it allows the images to be hardware accelerated
    - the returned image is 100% compatible with the display, regardless of what the input image is
    - BITMASK transparent images are an incredible amount faster than translucent images
    BITMASK means that a pixel is either fully transparent or it is fully opaque; there is no alpha blending being performed. Alpha blending in software rendering mode is very slow, so this may be the bottleneck that is bothering you.
    If you require your parallax images to be translucent then I wouldn't know how to get it to draw quicker in an applet, other than trying out java 6 update 10 to see if it fixes things.

  • How to display the steps of a sort algorithm??

    I'm having a lot of trouble trying to display the results of applying a merge sort to a set of 10 integers. The problem is not that I can't see anything on the text area within the applet, the problem is that I am getting a lot of repetitions and duplicates occuring. I have tried inserting the Display() method in various positions in the sort, I have set up a temporary array to compare the elements of the array before and after the particular step of the sort is applied and an if statement to display only if there are changes have happened to the array. Can anyone advise?? Here's the code for the sort, including my current attempt to get the sort diplayed in steps:
    public class MSort extends JFrame
    public MSort(int[] anArray, JApplet anApplet)
    a = anArray;
    applet = anApplet;
    ArrayUtil.Display(a,textArea);
    JumpLine(textArea);
    Sorts the array managed by this merge sorter
    public void sort()
    throws InterruptedException
    mergeSort(0, a.length - 1);
    textArea.append("End of Merge Sort");
    Sorts a range of the array, using the merge sort
    algorithm.
    @param from the first index of the range to sort
    @param to the last index of the range to sort
    public void mergeSort(int from, int to)
    throws InterruptedException
    if (from == to) return;
    int mid = (from + to) / 2;
    mergeSort(from, mid);
    mergeSort(mid + 1, to);
    merge(from, mid, to);
    Merges two adjacent subranges of the array
    @param from the index of the first element of the
    first range
    @param mid the index of the last element of the
    first range
    @param to the index of the last element of the
    second range
    public void merge(int from, int mid, int to)
    throws InterruptedException
    startPosition = from;
    endPosition = to;
    int n = to - from + 1;
    // size of the range to be merged
    // merge both halves into a temporary array b
    int[] b = new int[n];
    int i1 = from;
    // next element to consider in the first range
    int i2 = mid + 1;
    // next element to consider in the second range
    int j = 0;
    // next open position in b
    int[] oldArray = new int[a.length];
    System.arraycopy(a, 0, oldArray, 0, oldArray.length);
    // as long as neither i1 nor i2 past the end, move
    // the smaller element into b
    while (i1 <= mid && i2 <= to)
    if (a[i1] < a[i2])
              b[j] = a[i1];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    i1++;
    else
    b[j] = a[i2];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    i2++;
         pause(2);
    j++;
         for (int k=0; k < a.length-1; k++) {// method I've put in to                  try and compare the array b4 and after the sort
    if (a[k] != oldArray[k]){
    ArrayUtil.Display(a,textArea);
    JumpLine(textArea);
    // note that only one of the two while loops
    // below is executed
    // copy any remaining entries of the first half
    while (i1 <= mid)
    b[j] = a[i1];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    //ArrayUtil.Display(a,textArea);
                        //JumpLine(textArea);
    pause(2);
    i1++;
    j++;
    // copy any remaining entries of the second half
    while (i2 <= to)
    b[j] = a[i2];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
         } pause(2);
    i2++;
    j++;
    // copy back from the temporary array
    for (j = 0; j < n; j++)
    a[from + j] = b[j];
    for (int m=0; m < a.length-1; m++) {
    if (a[m] != oldArray[m]){
    ArrayUtil.Display(a,textArea);// method I've put in to try and compare the array b4 and after the sort
    JumpLine(textArea);
    pause(2);
    public void pause(int steps)
    throws InterruptedException
    if (Thread.currentThread().isInterrupted())
    throw new InterruptedException();
    applet.repaint();
    Thread.sleep(steps * DELAY);
    private int[] a;
    private int startPosition = -1;
    private int endPosition = -1;
         private JTextArea textArea = SortApplet1.getTextArea2();
    private JApplet applet;
    private static final int DELAY = 100;
    public static void JumpLine(JTextArea t){
         JTextArea TxtArea = t;
         TxtArea.append("\n\n");
    }

    see sample at http://lwh.free.fr/pages/algo/tri/tri.htm
    marvinrouge

Maybe you are looking for

  • FILE-XI-FILE problem

    Dear friends, Hope I can solve my problem through one of you. I am new to XI.  As suggested by many experts, I started FILE-XI-FILE. I am able to complete total steps given by blog /people/venkat.donela/blog/2005/03/02/introduction-to-simplefile-xi-f

  • Final Cut Pro X 10.1.2 background task

    Final Cut Pro X 10.1.2 background task is running without stopping, it's going from 0-100 in a second, very fast. And really doesn't let me work on my project. When I play a video on timeline, it plays the sound but doesnt view the video itself. What

  • Design & Split View Unavailable

    I will apologize up front for the length of this post. I wanted to give as comprehensive a picture as possible. I am running v. 8.0.2 on a OS X (10.4.8 - "Tiger"). I'm working on an intranet site using the company's newly approved template. Until a f

  • Partial data fetched in report when scheduled in background

    Experts, When I scheduled my report in foreground it displays all the data properly. But when I run the same in background, in the spool list it displays 260 pages whereas actually displays only 9 pages. The rest of the pages are not displayed in the

  • Spefications for Pdt Name,Serial Number and Pdt Number not working in HPSA

    HP technical support came and replaced a new motherboard on Feb 5, 2015. Also,  I have not being accessing HPSA for quite some time now and I am not aware how long has this take place.  When I access HPSA, under System Information, only Product Name,