基本Java问题,类更新GUI

基本Java问题,类更新GUI,java,user-interface,swing,Java,User Interface,Swing,我将尝试用示例来说明我的问题,我正在尝试创建一个Java程序,它将(最终)合并一个复杂的Swing GUI 我有Main.java public class Main extends JFrame implements ActionListener { JTextArea example; public Main() { //... Missing, basic swing code example = new JTextArea();

我将尝试用示例来说明我的问题,我正在尝试创建一个Java程序,它将(最终)合并一个复杂的Swing GUI

我有Main.java

public class Main extends JFrame implements ActionListener {

    JTextArea example;

    public Main()
    {

    //... Missing, basic swing code
       example = new JTextArea();
    //... example added to jpanel, jpanel added to jframe, jframe set visible etc.


    }

    public void actionPerformed(ActionEvent e) {


    if(e.getActionCommand().equalsIgnoreCase("Do Something!"))
    {
       new DoSomething();
    }

   public static void main(String[] args)  {

   SwingUtilities.invokeLater(new Runnable() {
    public void run() {
     new Main();
      }
    });

}
}

现在,我想让DoSomething()类更新我的示例JTextArea,最好的方法是什么

我可以将对example的引用传递给DoSomething(),所以DoSomething(example),但这似乎不太好。我还可以将“this”传递给DoSomething()并在Main中实现updateExample(String newString)方法,但这似乎也不太好


基本上,实现我想做的事情的最佳方式是什么?我正在编写的程序最终会变得比这复杂得多,我看不到一种方法可以让我做到这一点而不让它变得太混乱。

你似乎在寻找

我用你的话总结了一个小例子

import java.util.Observable;
import java.util.Observer;


public class Main implements Observer {
    private DoSomething businessClass;

    public Main() {
        businessClass = new DoSomething();
        businessClass.addObserver(this);
    }

    public static void main(String[] args) {
        Main main = new Main();
    }

    @Override
    public void update(Observable obs, Object obj) {
        // Do whatever you want to do with textarea or other UI components
    }
}

class DoSomething extends Observable {
    public DoSomething() {
        Object result = new Object();    // It can be any type not just an object
        // After finish...
        setChanged();
        notifyObservers(result);
    }
}

通过使用这个小模式,UI可以随时了解DoSomething类的状态,该类只需调用
notifyObservers
方法。因此,您的系统在保持健壮性的同时保持解耦

我用你的话总结了一个小例子

import java.util.Observable;
import java.util.Observer;


public class Main implements Observer {
    private DoSomething businessClass;

    public Main() {
        businessClass = new DoSomething();
        businessClass.addObserver(this);
    }

    public static void main(String[] args) {
        Main main = new Main();
    }

    @Override
    public void update(Observable obs, Object obj) {
        // Do whatever you want to do with textarea or other UI components
    }
}

class DoSomething extends Observable {
    public DoSomething() {
        Object result = new Object();    // It can be any type not just an object
        // After finish...
        setChanged();
        notifyObservers(result);
    }
}

通过使用这个小模式,UI可以随时了解DoSomething类的状态,该类只需调用
notifyObservers
方法。因此,您的系统在保持健壮性的同时保持解耦

在使用此功能后,我发现除非调用setChanged(),否则观察者不会被更新;在通知观察员之前();在处理这个问题之后,我发现除非调用setChanged(),否则观察者不会被更新;在通知观察员之前();