我使用LayerUI的自定义子类创建了一些加载指示。

该列表是StringWorker子类的arrayArray。它的get方法是一个阻塞调用,所以我认为这就是问题,只是不知道如何解决。该层启动了一个计时器,据我所知,计时器是在自己的线程中执行的,因此阻塞获取不应被干扰。

        loadingLayer.setVisible(true);
        lockComponents();
        for(int i = 0; i < list.size(); i++) {
            try {
                System.out.println("About to check "+i);
                if(list.get(i).get() == null) {

                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            } catch (ExecutionException e1) {
                e1.printStackTrace();
            }
        }
        unlockComponents();
        loadingLayer.setVisible(false);


仅在完成所有这些代码之后,“ loadingLayer”才会出现。

LoadingLayerUI类:

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComponent;
import javax.swing.Timer;
import javax.swing.plaf.LayerUI;
public class LoadingLayerUI extends LayerUI<JComponent> implements ActionListener {

/**
 *
 */
private static final long serialVersionUID = 827885062549399916L;
private boolean isShowing;
private Timer timer;


private String text;


@Override
public void paint(Graphics g, JComponent jc) {
    super.paint(g, jc);
    if(!isShowing)
        return;

    Graphics2D g2 = (Graphics2D) g.create();

    int w = jc.getWidth();
    int h = jc.getHeight();
    g2.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, .7f));
    g2.setPaint(Color.LIGHT_GRAY);
    g2.fillRect(0, 0, w, h);

    g2.setColor(Color.BLACK);
    Font font = new Font("Sans-Serif",Font.BOLD, 20);
    int width = g2.getFontMetrics(font).stringWidth("Loading");
    g2.setFont(font);
    if(text != null)
        g2.drawString(text, (w-width)/2, h/2);

    g2.dispose();
    jc.repaint();
}

public void setVisible(boolean set) {
    this.isShowing = set;
    if(isShowing) {
        timer = new Timer(200, this);
        timer.start();
    }
    else {
        timer.stop();
    }
}


@Override
public void actionPerformed(ActionEvent e) {
    if(!isShowing && timer.isRunning())
        timer.stop();

    if(text == null || text.equals("Downloading...")) {
        text = "Downloading";
    }
    else
        text += ".";

}
}

最佳答案

使用Swing时,应在单独的线程中执行长时间运行的任务。

这是本教程:http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

08-28 04:39