Swings jLabels即使我使用线程也不会更新



我正在为我的一个朋友写一个小笑话应用程序,我只是不明白为什么我的标签没有弹出,GUI也在冻结。我知道为了继续使用GUI,我必须使用线程进行后台操作,但即使在线程启动之前,它也会冻结。

Ui类:

private class CheckButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        check();
    }
}
public void check() {
    this.jbCheck.setEnabled(false);
    this.rand = (int) (Math.random() * 4) + 1;
            // Offending lines
    this.jlMessage1.setText("");
    this.jlMessage2.setText(this.messages.getString("wait_" + this.rand));
    this.jlMessage2.setForeground(Color.BLACK);
            // End of the offending lines
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        Future<Integer> task = service.submit(new BackgroundJob());
        ping = task.get();
    } catch (final InterruptedException ex) {
        ex.printStackTrace();
    } catch (final ExecutionException ex) {
        ex.printStackTrace();
    }
    this.jlMessage1.setText("Tienes " + ping + " ms de ping.");
    if (ping <= 125) {
        this.jlMessage2.setText(this.messages.getString("bien_" + this.rand));
        this.jlMessage2.setForeground(Color.GREEN);
    } else if (ping > 126 && ping <= 200) {
        this.jlMessage2.setText(this.messages.getString("medio_" + this.rand));
        this.jlMessage2.setForeground(Color.YELLOW);
    } else {
        this.jlMessage2.setText(this.messages.getString("mal_" + this.rand));
        this.jlMessage2.setForeground(Color.RED);
    }
    service.shutdownNow();
    this.jbCheck.setEnabled(true);
}

这是后台工作:

public class BackgroundJob implements Callable<Integer> {
private int ping;
@Override
public Integer call() throws Exception {
    ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "ping " + Constants.IP + " | find "Media"");
    pb.redirectErrorStream(true);
    try {
        Process p = pb.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = br.readLine().trim();
        ping = Integer.parseInt(line.split(" ")[8].split("ms")[0]);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return ping;
}

}

我不知道为什么它在调用Future<Integer> task = service.submit(new BackgroundJob()); 之前不更改标签

GUI不会更改标签,因为您在"主"线程中,负责重新绘制GUI。你打电话给

ExecutorService service = null;
try {
    service = Executors.newFixedThreadPool(1);
    Future<Integer> task = service.submit(new BackgroundJob());
    ping = task.get();

异步生成线程。但是呼叫CCD_ 2再次是阻塞操作。因此,您生成后台线程,但等待阻塞以获得结果。

最新更新