我有2个课程.java

主要的 :

public class Controller extends javax.swing.JFrame
{
    public static void updateProgressBar(int i) {
        jProgressBar1.setValue(i);
        jProgressBar1.repaint();
    }

    public static void main(String args[]) {

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Controller app = new Controller();
                app.setVisible(true);
                app.setResizable(false);
            }
        });
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        ChildModel model = new ChildModel();
        Thread t1 = new Thread(model);
        t1.start();
    }

    private javax.swing.JProgressBar jProgressBar1; //Initialized with Netbeans builder
}


我的ChildModel(ChildModel.java)计算了一些代码(大约需要10到20秒),我想显示父类(Controller.java)的进度。

这是我的ChildModel:

public class ChildModel implements Runnable
{
    public ChildModel(){ /* Something */ }

    public void complexMath()
    {
        //Lots of logic here
        Controller.updateProgression(purcent);
    }

    @Override
    public void run() {
        complexMath();
    }
}


问题显然是我的静态void updateProgressBar无法修改非静态变量。我怎样才能做到这一点?

最佳答案

jProgressBar1变量是一个实例变量,因此您不能从静态方法访问它。而且该方法不应是静态的:您想更新控制器中的进度,而不是所有Controller实例中的进度。

将对控制器的引用传递给ChildModel,并使用ChildModel中的此引用来更新进度条。还要记住,所有Swing交互都必须在EDT中完成,而不是在后台线程中完成。因此,代码应如下所示:

public class Controller extends javax.swing.JFrame
{
    public void updateProgressBar(int i) {
        jProgressBar1.setValue(i);
        // no need for repaint. The progress bar knows it must be repainted
        // when its value changes
    }

    public static void main(String args[]) {

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Controller app = new Controller();
                app.setVisible(true);
                app.setResizable(false);
            }
        });
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        ChildModel model = new ChildModel(this);
        Thread t1 = new Thread(model);
        t1.start();
    }

    private javax.swing.JProgressBar jProgressBar1; //Initialized with Netbeans builder
}

public class ChildModel implements Runnable
{

    private Controller controller;

    public ChildModel(Controller controller){
        this.controller = controller;
    }

    public void complexMath()
    {
        //Lots of logic here
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                controller.updateProgression(percent);
            }
        });
    }

    @Override
    public void run() {
        complexMath();
    }
}

09-28 08:51