【问题标题】:How to update Java Jframe controls from no-gui class using SwingWorker如何使用 SwingWorker 从无 gui 类更新 Java Jframe 控件
【发布时间】:2018-10-12 15:37:01
【问题描述】:

我已经问过这个问题,但需要更多详细信息。

How to update Java Jframe controls from no-gui class on real time

无法测试提出的答案,因为当 Windows 应用程序启动时,它看起来像大小 0,0,而当我最大化时,没有绘制控件。

无论如何,这是我原来的问题:

我想要做的(并寻找如何做)是将元素添加到我的 ListBox 来自实时的无 GUI 类,或者换句话说 “异步”,不会冻结我的应用程序。这清楚吗?我试过了 SwingWorker 和线程但没有结果。我能做的就是更新 所有过程完成后的列表框(显然我的应用程序冻结了 因为我的过程很长)。

这是我的架构:

  • 项目
  • __控制器
  • __商业
  • __Util
  • __查看

这是我的代码(试图重现提出的解决方案)

视图(使用 NetBeans 生成)

package view;

import MyController;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;

public class MyView extends javax.swing.JFrame {

    static MyController controller;

    public MyView(DefaultListModel<String> model) {

        initComponents();
        pack();
        setVisible(true);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        btnRun = new javax.swing.JButton();
        jscrlLog = new javax.swing.JScrollPane();
        jlstLog = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnRun.setText("Run");
        btnRun.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRunActionPerformed(evt);
            }
        });

        jscrlLog.setViewportView(jlstLog);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(159, 159, 159)
                .addComponent(btnRun)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jscrlLog, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnRun)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jscrlLog, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void btnRunActionPerformed(java.awt.event.ActionEvent evt) {                                       
        controller.runProcess();
    }                                      

    public void addButtonListener(ActionListener listener) {
        btnRun.addActionListener(listener);
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MyView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MyView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MyView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MyView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                controller = new MyController();
            }
        });


    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btnRun;
    private javax.swing.JList jlstLog;
    private javax.swing.JScrollPane jscrlLog;
    // End of variables declaration                   
}

商业

package business;

import MyLog;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.SwingWorker;

public class MyBusiness {

    private int counter = 0;
    private DefaultListModel<String> model;
    private MyLog log;

    public MyBusiness(DefaultListModel<String> model) {
        this.model = model;a
    }

    public void runProcess() {
        SwingWorker<Void, String> worker = new SwingWorker<Void, String>() {
            @Override
            protected Void doInBackground() throws Exception {
                for (int i = 0; i < 10; i++) {
                    publish("log message number " + counter++);
                    Thread.sleep(2000);
                }

                return null;
            }

            @Override
            protected void process(List<String> chunks) {
                // this is called on the Swing event thread
                for (String text : chunks) {
                    model.addElement("");
                }
            }
        };
        worker.execute();
    }

}

日志(模型)

package util;

import javax.swing.DefaultListModel;

public class MyLog {

    private DefaultListModel<String> model;

    public MyLog() {
        model = new DefaultListModel<String>();
    }

    public DefaultListModel<String> getLog(){
        return model;
    }

}

【问题讨论】:

  • initComponents() 永远不会被调用。
  • 重要的旁注:构造函数参数DefaultListModel&lt;String&gt; model 从未使用过。另请仔细阅读minimal reproducible example。没必要贴这么长的代码只是为了演示没有绘制的组件。准备 mcve 不仅使帮助更容易,它还是一个强大的调试工具。很多情况下,在准备一份的时候,你很可能会发现问题。
  • @c0der 我更新了我的视图,现在它加载正常,但按下按钮时不起作用...我不明白你的意思 DefaultListModel&lt;String&gt; model 从未使用过

标签: java swing asynchronous model-view-controller jframe


【解决方案1】:

当 Windows 应用程序启动时,它看起来像大小 0,0,而当我最大化时,没有绘制控件。

public MyView(DefaultListModel<String> model) {
    setVisible(true);
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

我所看到的只是你使框架可见。我看不到您在哪里向框架添加了组件。那是你在哪里调用过 initComponents()?

在使框架可见之前,需要将组件添加到框架中。而且你需要在它可见之前打包()框架。

【讨论】:

  • 好的,我明白了,我的应用程序运行但在按下按钮时不执行...知道吗?
  • @WesleyRomero,所以您的原始问题已得到解答。很高兴这个建议有所帮助。不要忘记通过单击复选标记“接受”答案,以便人们知道问题已解决。如果您有其他问题,那么您应该提出一个单独的问题。您应该在问题中包含正确的minimal reproducible example,而不仅仅是像您在此处所做的代码的核心转储。你需要学会简化问题。我们不知道“按下按钮时不执行”是什么意思。所以简化代码来演示你的问题。
  • @camickr:在上一个类似问题上,他曾被要求提供 MCVE,也向他提供了 MCVE
【解决方案2】:

有两个主要问题会阻止日志出现在JList 中:

一个。模型从未使用过。太使用它添加一个model 字段:

private DefaultListModel<String> model;

public MyView(DefaultListModel<String> model) {
    this.model = model;
    initComponents();
}

并将模型分配给JList:

//change  jlstLog = new JList<>();  to  
jlstLog = new JList<>(model); 

b.这个方法

public void runProcess() {

    view.addButtonListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            business.runProcess();
        }}
    );
}

永远不会被调用,所以按钮没有动作监听器。
可以查看清除此问题的完整代码here

关于询问的其他一些问题
最初的问题是answered。 我认为在回答完问题后更改问题并不是一个好习惯。
它使问题的答案变得无关紧要,并且投入其中的工作对未来的读者没有帮助。 请坚持“一个帖子一个问题”的政策。
在 cmets 中也多次强调了 mcve 的重要性。 mcve 应该展示问题,而不是您的应用程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多