猿问

Swing Worker 无法更新模态 jdialog 中的 GUI 组件

我有一个带有进度条和文本区域的模态 Jdialog。我正在启动一个 Swing Worker 来执行一些后台任务并使用发布过程更新 jdialog 中的文本区域。但是,在运行程序时,我观察到即使调用了 process 方法,它仍然没有更新 jdialog 中的文本区域。另外,请注意,我在 swing worker 的 done 方法中关闭了 jdialog,它工作正常。谁能告诉我为什么没有从(SwingWorker 的)流程方法进行 gui 更新?


JDialog 类 -


public class ProgressDialog extends JDialog {


private static final long serialVersionUID = 1L;

private GridBagLayout gridBag;

private GridBagConstraints constraints;

private ProgressDialog.ProgressBar progressBar;

private JScrollPane scrollPane;

private JTextArea textArea;


ProgressDialog(Frame owner, String title, boolean modal, int numTasks) {


    super(owner,title,modal);


    gridBag = new GridBagLayout();

    constraints = new GridBagConstraints();


    this.progressBar = new ProgressDialog.ProgressBar();

    this.progressBar.init(numTasks);


    this.textArea = new JTextArea(10,30);

    this.textArea.setEditable(false);

    this.scrollPane = new JScrollPane(this.textArea);

    this.scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    this.scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);


    this.setLayout(gridBag);


    constraints.gridx = 0;

    constraints.gridy = 0;

    gridBag.setConstraints(progressBar, constraints);


    constraints.gridx = 0;

    constraints.gridy = 1;

    constraints.insets = new Insets(10,0,10,0);

    gridBag.setConstraints(scrollPane, constraints);



    this.add(progressBar);

    this.add(scrollPane);

    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    this.setSize(400, 300);

    this.setLocationRelativeTo(null);

}


class ProgressBar extends JProgressBar {


    ProgressBar() {


    }


    void init(int numTasks) {

        setMaximum(numTasks);

        setStringPainted(true);

        setValue(0);

    }


    void setProgress(int taskCompleted) {

        int totalTasks = getMaximum();

        setValue(taskCompleted);

        setString(taskCompleted+"/"+totalTasks);

    }

}


翻过高山走不出你
浏览 99回答 2
2回答

达令说

一个巨大的问题就在这里:protected void done() {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(5000);&nbsp; &nbsp; } catch (InterruptedException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }&nbsp; &nbsp; pDialog.dispose();}在 EDT 或事件调度线程上调用worker 的done()方法,并且您知道当您休眠该线程时会发生什么——整个 GUI 进入休眠状态并变得完全没有响应。如果您想延迟对话框的处理并保持您的 GUI 正常运行,请不要这样做,实际上永远不要调用Thread.sleepEDT。选项1:相反,在大多数其他 Swing 延迟策略中,使用 Swing Timer,例如,类似这样的东西(代码未测试):protected void done() {&nbsp; &nbsp; int timerDelay = 5000;&nbsp; &nbsp; new Timer(timerDelay, new ActionListener() {&nbsp; &nbsp; &nbsp; &nbsp; public void actionPerformed(ActionEvent e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pDialog.dispose();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ((Timer) e.getSource).stop();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }).start();}如果您不熟悉 Swing Timer 的使用,请查看Swing Timer 教程选项 2:把你放在Thread.sleep(5000)你方法的最后doInBackground(),就在之前return null;另一个问题:您正在使用发布/处理方法对,但只使用了一次,这违背了它的目的。也许您打算在轮询 while 循环中调用发布?当然你只能调用get()一次,但是有没有另一种方法可以从你正在调用的正在运行的进程中提取信息?如果是这样,则需要间歇性地获取信息,无论是在轮询 while 循环中,还是通过任何允许您提取临时结果的过程。例如:import java.awt.BorderLayout;import java.awt.Dialog.ModalityType;import java.awt.Dimension;import java.awt.Window;import java.awt.event.ActionEvent;import java.beans.*;import java.util.ArrayList;import java.util.List;import java.util.concurrent.*;import javax.swing.*;public class TestProgressDialog extends JPanel {&nbsp; &nbsp; private static final long serialVersionUID = 1L;&nbsp; &nbsp; private ProgressDialog pDialog;&nbsp; &nbsp; private JSpinner taskNumberSpinner = new JSpinner(new SpinnerNumberModel(10, 1, 20, 1));&nbsp; &nbsp; public TestProgressDialog() {&nbsp; &nbsp; &nbsp; &nbsp; setPreferredSize(new Dimension(800, 650));&nbsp; &nbsp; &nbsp; &nbsp; add(new JButton(new AbstractAction("Launch Dialog") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; private static final long serialVersionUID = 1L;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public void actionPerformed(ActionEvent e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Window owner = SwingUtilities.windowForComponent(TestProgressDialog.this);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String title = "Dialog";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ModalityType modal = ModalityType.MODELESS;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int numTasks = (int) taskNumberSpinner.getValue();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pDialog = new ProgressDialog(owner, title, modal, numTasks);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pDialog.pack();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pDialog.setLocationByPlatform(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pDialog.append("Initializing background tasks\n");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; MyWorker myWorker = new MyWorker(numTasks, pDialog);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; myWorker.addPropertyChangeListener(new WorkerListener(pDialog));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; myWorker.execute();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pDialog.setVisible(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }));&nbsp; &nbsp; &nbsp; &nbsp; add(new JLabel("Number of Tasks:"));&nbsp; &nbsp; &nbsp; &nbsp; add(taskNumberSpinner);&nbsp; &nbsp; }&nbsp; &nbsp; private static void createAndShowGui() {&nbsp; &nbsp; &nbsp; &nbsp; TestProgressDialog mainPanel = new TestProgressDialog();&nbsp; &nbsp; &nbsp; &nbsp; JFrame frame = new JFrame("Test Progress Dialog");&nbsp; &nbsp; &nbsp; &nbsp; frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);&nbsp; &nbsp; &nbsp; &nbsp; frame.getContentPane().add(mainPanel);&nbsp; &nbsp; &nbsp; &nbsp; frame.pack();&nbsp; &nbsp; &nbsp; &nbsp; frame.setLocationByPlatform(true);&nbsp; &nbsp; &nbsp; &nbsp; frame.setVisible(true);&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; SwingUtilities.invokeLater(() -> createAndShowGui());&nbsp; &nbsp; }}interface Progressable {&nbsp; &nbsp; void setProgress(int progress);&nbsp; &nbsp; void append(String text);}class ProgressDialog extends JDialog implements Progressable {&nbsp; &nbsp; private static final long serialVersionUID = 1L;&nbsp; &nbsp; private JProgressBar progressBar = new JProgressBar(0, 100);&nbsp; &nbsp; private JTextArea textArea = new JTextArea(10, 30);&nbsp; &nbsp; private JScrollPane scrollPane = new JScrollPane(textArea);&nbsp; &nbsp; ProgressDialog(Window owner, String title, ModalityType modal, int nunTasks) {&nbsp; &nbsp; &nbsp; &nbsp; super(owner, title, modal);&nbsp; &nbsp; &nbsp; &nbsp; progressBar.setStringPainted(true);&nbsp; &nbsp; &nbsp; &nbsp; scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);&nbsp; &nbsp; &nbsp; &nbsp; add(progressBar, BorderLayout.PAGE_START);&nbsp; &nbsp; &nbsp; &nbsp; add(scrollPane);&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void append(String text) {&nbsp; &nbsp; &nbsp; &nbsp; textArea.append(text);&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void setProgress(int progress) {&nbsp; &nbsp; &nbsp; &nbsp; progressBar.setValue(progress);&nbsp; &nbsp; }}class MyCallable implements Callable<String> {&nbsp; &nbsp; private static final long MAX_DUR = 6 * 1000;&nbsp; &nbsp; private static final long MIN_DUR = 1000;&nbsp; &nbsp; private String text;&nbsp; &nbsp; public MyCallable(String text) {&nbsp; &nbsp; &nbsp; &nbsp; this.text = text;&nbsp; &nbsp; }&nbsp; &nbsp; public String getText() {&nbsp; &nbsp; &nbsp; &nbsp; return text;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String call() throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; // just wait some random delay and then return a String&nbsp; &nbsp; &nbsp; &nbsp; long timeout = (long) (Math.random() * MAX_DUR + MIN_DUR);&nbsp; &nbsp; &nbsp; &nbsp; TimeUnit.MILLISECONDS.sleep(timeout);&nbsp; &nbsp; &nbsp; &nbsp; return text + " time out: " + timeout;&nbsp; &nbsp; }}class WorkerListener implements PropertyChangeListener {&nbsp; &nbsp; private Progressable progressable;&nbsp; &nbsp; public WorkerListener(Progressable progressable) {&nbsp; &nbsp; &nbsp; &nbsp; this.progressable = progressable;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public void propertyChange(PropertyChangeEvent evt) {&nbsp; &nbsp; &nbsp; &nbsp; if (evt.getPropertyName() != null && evt.getPropertyName().equals("progress")) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int progress = (int)evt.getNewValue();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; progressable.setProgress(progress);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}class MyWorker extends SwingWorker<Void, String> {&nbsp; &nbsp; private Progressable progressable;&nbsp; &nbsp; private List<Future<String>> futures = new ArrayList<>();&nbsp; &nbsp; private CompletionService<String> completionService;&nbsp; &nbsp; private int numTasks;&nbsp; &nbsp; // private BlockingQueue<Future<String>> completionQueue;&nbsp; &nbsp; public MyWorker(int numTasks, Progressable progressable) {&nbsp; &nbsp; &nbsp; &nbsp; this.numTasks = numTasks;&nbsp; &nbsp; &nbsp; &nbsp; this.progressable = progressable;&nbsp; &nbsp; &nbsp; &nbsp; ExecutorService service = Executors.newFixedThreadPool(numTasks);&nbsp; &nbsp; &nbsp; &nbsp; completionService = new ExecutorCompletionService<>(service);&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < numTasks; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; futures.add(completionService.submit(new MyCallable("My Callable " + i)));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; service.shutdown();&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; protected Void doInBackground() throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; while (futures.size() > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Future<String> future = completionService.take();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; futures.remove(future);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int progress = (100 * (numTasks - futures.size())) / numTasks;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; progress = Math.min(100, progress);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; progress = Math.max(0, progress);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setProgress(progress);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (future != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; publish(future.get());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; protected void process(List<String> chunks) {&nbsp; &nbsp; &nbsp; &nbsp; for (String chunk : chunks) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; progressable.append(chunk + "\n");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public Progressable getpDialog() {&nbsp; &nbsp; &nbsp; &nbsp; return progressable;&nbsp; &nbsp; }}

郎朗坤

这里的问题是您的 Jdialog 框是模态的。每当弹出(或 JDialog)是setModal(true)EDT 线程被阻塞。这就是当使用 modal 弹出时用户将无法执行任何操作的方式true。您必须制作它setmodal(false),然后在弹出窗口中更新内容,然后再制作它setmodal(true)。
随时随地看视频慕课网APP

相关分类

Java
我要回答