DefaultListModel 是否覆盖了我的动作监听器中的动作顺序?

Is DefaultListModel over-riding the order of actions in my actionlistener?

我的 JAVA 程序有一段,您在其中单击一个按钮,actionListener 应该经过以下过程;

  1. 将按钮上的文本从 "Start" 更改为 "Standby"
  2. 向面板添加一个标签,说明进程已启动
  3. 执行一个方法(对数据进行排序,returns 通过将元素添加到 defaultListModel JList,最后
  4. 将按钮上的文本从 "Start" 更改为 "Complete"

如下

uploadNotamButton.addActionListener((ActionEvent e) -> {
        if(e.getSource()==uploadNotamButton)
            uploadNotamButton.setText("STANDBY");
        progressLabel.setText("Process Has Begun, standby...");
        progressLabel.setVisible(true);

        uploadNotams();

        uploadNotamButton.setText("COMPLETE");
    });

但是,当我按下按钮时,按钮文本没有改变,标签没有显示,但是方法执行了。只有当该方法完成时,按钮文本才会更改为 "Complete"(从未显示 "STANDBY")并且显示 "the process has begun, standby" 的标签(当该过程完成时)。

这是defaultlistmodel优先于一切的特性还是我编码经验不足?

此外,在该方法中分析的数据会一次性显示在 JList 中,而不是一次显示每个元素。如果数据在分析时显示在列表中,它至少会表明正在发生某些事情。这对 defaultListModel 来说是不可能的吗?

非常感谢
PG

Is this a feature of defaultlistmodel that takes priority over everything or my coding inexperience?

这与 DefaultListModel 无关,与 Swing 是单线程的有关。您的长 运行ning 进程正在 运行 Swing 事件线程上,阻止该线程执行其必要的操作,包括在您的 GUI 上绘制文本和图像以及与用户交互。

解决方案是使用一个后台线程,例如可以通过 SwingWorker 获得,运行在这个后台线程中添加您的长代码,运行ning 代码,向工作线程添加一个 PropertyChangeListener 以完成后收到通知,然后回复此通知。

例如(代码未测试)

uploadNotamButton.addActionListener((ActionEvent e) -> {
    // if(e.getSource()==uploadNotamButton)
    uploadNotamButton.setText("STANDBY");
    progressLabel.setText("Process Has Begun, standby...");
    progressLabel.setVisible(true);

    // create worker to do background work
    SwingWorker<Void, Void> worker = new SwingWorker<>() {
        @Override
        protected Void doInBackground() throws Exception {
            // this is all done within a background thread
            uploadNotams();  // don't make any Swing calls from within this method
            return null;
        }
    };

    // get notified when the worker is done, and respond to it
    worker.addPropertyChangeListener(new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getNewValue == SwingWorker.StateValue.DONE) {
                uploadNotamButton.setText("COMPLETE");

                // the code below needs to be surrounded by a try/catch block
                // and you'll need to handle any exceptions that might be caught
                ((SwingWorker) evt.getSource()).get();
            }
        }
    });
    worker.execute();  // run the worker
});