仅本地设备Applet运行异常:未调用repaint但paint重复执行求助
Let's tackle your two issues one by one:
Applets are outdated technology at this point, so most device-specific failures tie back to environment mismatches. Here are actionable checks to fix this:
- Java Version Compatibility: Java 9 and later completely removed support for Applets. Verify you're using a Java 8 or earlier JRE/JDK by running
java -versionin your terminal/command prompt. - Use the Official Applet Viewer: Modern browsers (Chrome, Firefox, Edge) no longer support Java plugins. Instead, use the
appletviewertool included with older JDKs—runappletviewer your-html-file.htmlto launch the applet directly. - Clear Java Cache: Corrupted cached applet data can cause loading issues. Open your Java Control Panel → General → Temporary Internet Files → Settings → Delete Files to wipe cached applets.
- Check Local Permissions: Ensure your user account has read/write access to the directory where your applet files are stored. Permission blocks can silently prevent the applet from loading.
paint() runs twice without calling repaint() First off, this is expected behavior in AWT applets. The paint() method is called automatically by the AWT event dispatch thread in multiple scenarios, not just when you explicitly call repaint(). Common triggers for duplicate calls include:
- Initial rendering when the applet first becomes visible.
- A second system-initiated repaint after the applet finishes loading, to ensure full component rendering (especially if layout adjustments happened).
- If the applet window is resized, moved, or uncovered after being hidden.
How to resolve this:
If you don't want non-drawing logic (like your System.out.println("done")) to run multiple times, move that code to lifecycle methods like init() or start()—these run only once during the applet's lifecycle:
import java.awt.* ; import java.awt.event.* ; import java.applet.* ; public class game extends Applet { @Override public void init() { // Runs once when the applet initializes System.out.println("done"); } @Override public void paint(Graphics g){ // Keep only drawing-related code here // Example: g.drawString("Hello Applet", 10, 20); } }
If you absolutely need a one-time task inside paint() (not recommended, since paint() is for rendering), use a boolean flag to track execution:
import java.awt.* ; import java.awt.event.* ; import java.applet.* ; public class game extends Applet { private boolean hasExecuted = false; @Override public void paint(Graphics g){ if (!hasExecuted) { System.out.println("done"); hasExecuted = true; } // Drawing code here } }
Remember: The paint() method is designed exclusively for graphics rendering. Stick to the applet's lifecycle methods for setup or one-time tasks—it's the standard, maintainable approach.
内容的提问来源于stack exchange,提问作者Puru Arora

