本文介绍了Java使用MediaTracker读写图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我写了一个代码来获取图像(使用 jfileChooser),然后将它保存为硬盘上的新图片,并且奏效了.但是当我尝试在其他计算机或系统上使用此代码时,它不起作用.MediaTracker 总是包含一个错误,但我无法显示有关问题所在的可读信息,而且我不知道如何解决此问题(但我不会再阅读此来源).

recently I wrote a code to get image (using jfileChooser) and then save it as new picture on hard Drive, and that worked. But when I try to use this code on other computers, or system it didn't work. The MediaTracker always contain a error but I can't display readable information about what going wrong, and I dont have idea how to fix this issue (but I don't won't to read again this source).

非常感谢您提供可能做错的任何想法.

Thanks a lot for any ideas what can do wrong.

    JFileChooser jfc = new JFileChooser();
    jfc.setCurrentDirectory(new File("C:\\"));
    jfc.showOpenDialog(null);
    File sf = jfc.getSelectedFile();
    if( sf==null )
        return false;

    String iconName = sf.getAbsolutePath();
    URL imgUrl = null;
    try
    {
        imgUrl = new URL("file:\\"+iconName);
    }
    catch(MalformedURLException murle){
    //plujemy!
        System.out.println(murle);
    }
    imageA = getToolkit().getImage(imgUrl);
    MediaTracker mt = new MediaTracker(this);
    try
    {
        mt.addImage(imageA,0);
        mt.waitForAll();
    }
    catch (InterruptedException ie)
    {
        ie.printStackTrace(new PrintStream(System.out));
        return false;
    }
    if(mt.isErrorAny()){
        return false;
    }else{
        return true;
    }

推荐答案

猜测,没有完整的例子,你对 waitForAll() 的调用阻塞了 事件调度线程.请注意 MediaTracker API 示例在后台线程中等待.或者,使用 SwingWorker 加载图像,如此处所示.

At a guess, absent a complete example, your call to waitForAll() is blocking the event dispatch thread. Note how the MediaTracker API example waits in a background thread. As an alternative, use SwingWorker to load the image(s), as shown here.

这篇关于Java使用MediaTracker读写图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 14:24