简体   繁体   English

显示带有gif的自定义加载对话框

[英]Show custom loading dialog with gif

I am trying to get my application to display a simple loading dialog so users know when a time intensive process is working and when its done. 我试图让我的应用程序显示一个简单的加载对话框,以便用户知道什么时候需要耗费时间,什么时候完成。 I just want it to show a simple "loading" using a gif I downloaded. 我只希望它使用我下载的gif文件显示一个简单的“加载”。 I already tried using only text and it still doesn't work. 我已经尝试过仅使用文本,但仍然无法正常工作。

I can get the dialog to display (and disappear) when I want it to, the problem is nothing will display on the dialog (or frame) after displaying it. 我可以使对话框在需要时显示(并消失),问题是显示对话框(或框架)后什么也不会显示。 I have tried many different techniques and all give the same result, a blank dialog. 我尝试了许多不同的技术,并且都给出了相同的结果,一个空白对话框。

I finally made a separate class to display the dialog (with loading gif) and I got it to display properly (by itself), but when I run it from my main application, it shows a black dialog again. 最后,我做了一个单独的类来显示对话框(加载gif),并使其正确显示(本身),但是当我从主应用程序运行它时,它又显示了一个黑色对话框。 I tested putting the gif into a JOptionPane and it works, the problem with that is I can't close it at will. 我测试过将gif放入JOptionPane中,并且可以正常工作,但问题是我无法随意关闭它。

Here is my custom code. 这是我的自定义代码。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import java.util.logging.*;
import org.w3c.dom.*;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import javax.swing.filechooser.FileNameExtensionFilter;

public class Loader implements Runnable  {

    final JFileChooser jfc = new JFileChooser();
    static JFrame frame = new JFrame();
    Frame parentUI = new  Frame();
    JDialog dialog = new JDialog();
    JLabel lbl_filename = new JLabel();
    JLabel lbl_path = new JLabel();

    static Loader load = new Loader(null);


    public static void main(String[] args) throws InterruptedException, InvocationTargetException {
        load.run();
        frame.setVisible(true);
    } 

    public Loader(Frame parent) {
        init();
        parentUI = parent;
    }

    @Override
    public void run() {
        createDialog(parentUI);
    }  

    public final void init() {
        JButton btn = new JButton("Open");

        frame.setTitle("Loader Test");
        frame.setSize(500, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setLayout(new FlowLayout());

        btn.addActionListener(new Action1());

        frame.add(btn);
        frame.add(lbl_filename);
        frame.add(lbl_path);
    }

    class Action1 implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {

            openFile();
            load.Close();
        }
    }

    private void createDialog(final Frame parent) {

        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setTitle("Loader");

        URL url = this.getClass().getResource("/resource/loader.gif");
        Icon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);
        dialog.add(label);

        dialog.pack();
        dialog.setLocationRelativeTo(parent);
    }


    public void Show(Boolean visible) {
        this.run();
        dialog.setVisible(visible);
    }

    public void Close() {
        dialog.setVisible(false);
    }

    private void setJFCFilter(String file, String ext) {
        FileNameExtensionFilter filter = new FileNameExtensionFilter(file, ext);
        jfc.setFileFilter(filter);
    }

    private void openFile() {
        File default_dir = new File(".");
        jfc.setCurrentDirectory(default_dir);
        setJFCFilter("Scalable Vector Graphics", "svg");

        int returnVal = jfc.showOpenDialog(parentUI);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            String path = jfc.getSelectedFile().getAbsolutePath();
            String fileName = jfc.getSelectedFile().getName();

            lbl_filename.setText(fileName);
            lbl_path.setText(path);

            load.Show(true);
            createDoc(path);
            load.Close();

        }
    }

    private void createDoc(String file) {
        try {
            NodeList svgIDPaths;

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(file);

            String xpathIDExp = "//g/@id";

            XPathFactory xpf = XPathFactory.newInstance();
            XPath xpath = xpf.newXPath();
            XPathExpression expression = xpath.compile(xpathIDExp);

            svgIDPaths = (NodeList)expression.evaluate(doc, XPathConstants.NODESET);

        } catch (Exception ex) {
            Logger.getLogger(Loader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}  

Edit: Use this file for testing -> svg_test.svg 编辑:使用此文件进行测试-> svg_test.svg

I have tried calling it like this: 我试过这样称呼它:

loader.show(true);

And also in its own thread like this: 而且在它自己的线程中是这样的:

private void load(final Boolean visible) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            loader.show(visible);
        }
    });

    t.start();
}

Neither method works and gives me the same result, a blank dialog. 两种方法都不起作用,并且给我相同的结果,即空白对话框。 I have had this issue in the past, but just gave up and removed it (loading dialog). 我过去曾遇到过此问题,但只是放弃并删除了它(加载对话框)。 I have tried it with a progress bar and simple text, nothing seems to work. 我用进度条和简单的文本尝试了一下,似乎没有任何效果。

Also I tried it in a JOptionPane and it worked, but that's not desirable (I want to close/open when I want not via a button click). 我也曾在JOptionPane中尝试过它,但它不起作用(但是我不想通过按钮单击来关闭/打开)。

 private void load() {
        ImageIcon icon = new ImageIcon(MainForm.class.getResource("/resource/loader.gif").getFile());
        JOptionPane.showMessageDialog(null, "Loading...", "Loader", JOptionPane.INFORMATION_MESSAGE, icon);
    }

I am aware you can't run multiple dialogs on the EDT and have to use a separate thread, but I'm using a separate thread and its not working (it works by itself). 我知道您不能在EDT上运行多个对话框,而必须使用单独的线程,但是我使用的是单独的线程,并且该线程不起作用(它可以单独工作)。

(Also note I have one main application (frame) that is running/opening this second dialog). (还要注意,我有一个正在运行/打开第二个对话框的主应用程序(框架))。

Any assistance is appreciated. 任何帮助表示赞赏。

You look to have a Swing threading issue where you have long-running code on the event thread messing up drawing of images, and my guess is that the long running code is in your createDoc method. 您似乎遇到了Swing线程问题,在事件线程上有长时间运行的代码弄乱了图像的绘制,我想这是长时间运行的代码在createDoc方法中。 Consider calling that from a background thread, such as from a SwingWorker, and calling close on your load object only after the worker has completed its work. 考虑从诸如SwingWorker之类的后台线程调用该函数,并仅在worker完成其工作之后才对load对象调用close。 For example something like so: 例如这样的事情:

class Action1 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {

        openFile();
        // load.Close();  // get rid of this
    }
}

// .......

private void openFile() {

    // ....

    load.Show(true);  // load dialog on event thread

    new SwingWorker<Void, Void>() {
        protected Void doInBackground() throws Exception {
            createDoc(path);  // call this from background thread
            return null;
        };

        protected void done() {
            load.Close();  // only call this once createDoc has completed
            // probably should call get() in here to catch all exceptions
        };
    }.execute();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM