Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

java - MediaTracker - how to use it, what are the benefits, or is there an alterative?

In the codebase we inherited the usage of MediaTracker was always done locally in each code block.

new MediaTracker(new Canvas());
mediatracker.addImage(i, 1);
try {
    mediatracker.waitForAll();
} catch (InterruptedException e) { }
mediatracker.removeImage(i);

Deciding this was inefficient, I eventually replaced it with a static instance and method:

final static protected MediaTracker mediatracker = new MediaTracker(new Canvas());

static protected void checkImageIsReady(Image i) {
    mediatracker.addImage(i, 1);
    try {
        mediatracker.waitForAll();
    } catch (InterruptedException e) { }
    mediatracker.removeImage(i);
}

Thus far there have been no ill effects.

There is another possible approach - to attach the MediaTracker to each component (usually a Frame or JFrame) which is strongly implied as the approach to take by the constructor documentation.

So I have 2 questions:

  1. How and why to use MediaTracker?

  2. What is the alternative?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

MediaTracker was useful in 1995. Back then the primary GUI use of java was Applets, and Applets would usually load images slowly over the network.

To make it easier for Applet writers, java gave us a nice MediaTracker api which would download images in the background, tracking when they were done, and even give notifications when images were partially loaded. The MediaTracker API meant Applet writers didn't have to block the application while images slowly downloaded, and didn't have to write complicated threading code to load images in background threads.

These days you can typically load images synchronously, and it is best to use ImageIO. This is especially true for the common case where images are loaded from the local file system.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...