Java Applet Thread Animation

前端 未结 2 734
南旧
南旧 2021-01-15 03:12

I am gone through some of code java applet and animation, i write the following code :

import java.applet.*;
import java.awt.*;

/*

        
                      
相关标签:
2条回答
  • 2021-01-15 03:24

    Yes it will flicker. You will have to solve this problem using the concept of DoubleBuffering. It means that the image to be drawn is already buffered before its drawn on screen. It will remove the flickering effect.

    0 讨论(0)
  • 2021-01-15 03:40
    • Don't directly paint over top level container. Use JPanel to paint on it.
    • Don't use Thread.sleep(). It's better to use Swing Timer for animation.
    • Override paintComponent() method of JPanel for custom painting.
    • Don't forget to call super.paintComponent() inside overridden paintComponent method.

    Instead of infinite loop try with Swing Timer.

    Please have a look at How to Use Swing Timers

    sample code:

    import java.applet.Applet;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    /*
     * <applet code="AppletDemo" width = 200 height = 100></applet>
     */
    
    public class AppletDemo extends Applet {
        String msg = "Text Animating from right to left...";
        int state;
        boolean stopFlag;
        int msgX = 200;
        String s;
        boolean diff;
        JPanel panel;
    
        public void init() {
            setBackground(Color.cyan);
            setForeground(Color.black);
            panel = new JPanel() {
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponents(g);
                    g.drawString(msg, msgX, 20);
                    showStatus(diff + "Text at " + msgX + ",20");
                }
    
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(200, 40);
                }
            };
            add(panel);
    
            int delay = 10; // milliseconds
            ActionListener taskPerformer = new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    if (msgX >= -150)
                        msgX--;
                    else
                        msgX = 200;
                    repaint();
                }
            };
            Timer timer = new Timer(delay, taskPerformer);
            timer.setRepeats(true);
            timer.start();
        }
    
    }
    

    enter image description here

    Find a Sample code here

    enter image description here

    0 讨论(0)
提交回复
热议问题