如何将用户输入从 GUI 传递到主类



我刚刚开始使用Java Swing,我遇到了和上次一样的问题。我想编写一个程序来读取一些用户输入,执行算法并显示结果。该程序必须使用两个不同的用户界面(控制台和带有Java Swing的GUI)。

目前我有一个带有算法的类包(我可以传入用户输入并获取结果),一个包含主类的类,一个控制台接口的类和一个GUI的类(从JFrame扩展)。一些代码:


public class Algorithm {
//a lot of code
}
public class MainClass {
    public static void main(...) {
        Algorithm algorithm = new Algorithm();
        //use either console or GUI and read user input
        algorithm.execute(user input);
        algorithm.getResult();
        //display result on console/GUI
    }
}
public class GUI extends JFrame implements ActionListener {
}

My Problem is that I don't know how to pass the user input (text, scalers and radio buttons, button) from the GUI to the algorithm and how to display the result on the GUI.

Do I have to pass an instance of Algorithm to the GUI and call the methods of Algorithm from GUI?
Or is it possible to implement the ActionsListener in MainClass (where I have an instance of Algorithm)? If I choose this way of implementation, how can i pass the result of the Algorithm back to the GUI?
Or should i change the whole implementation? :D

Short answer: Don't (at least not to the Main class).

Long answer: There is a pattern called Model-View-Controller (MVC) which explains how to get data from the user, do something with it and display it again. This link (and the whole site in general) is a good point to start: http://martinfowler.com/eaaDev/uiArchs.html

Applied to your code sample:

public class Algorithm {
//a lot of code
}
public class MainClass {
    public static void main(...) {
        Algorithm algorithm = new Algorithm();
        GUI g = new GUI(algorithm );
    }
}
public class GUI extends JFrame implements ActionListener {
    private Algorithm algo;
    public GUI(Algorithm a) { this.algo = a; }
}

Algorithm在这里扮演模型的角色,GUI是控制器和视图的组合。

由于您将算法很好地封装在自己的类中,因此应该很容易实例化算法类型的对象以响应按钮单击您的 GUI 并在那里执行算法。主要方法只决定GUI是否必要并启动它。

因此,如果您在 GUI 上有一个名为 calculate 的按钮,那么:

  calculate.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
               //get the user input from the JFrame
               Algorithm algorithm = new Algorithm();
               algorithm.execute(user input);
               algorithm.getResult();
               //display results on the JFrame
          }
  });

从 JTextField 等获取输入非常简单

  mytextfield.getText();

将一些值写入 JLabel 以显示是:

  mylabel.setText("Some Text");

您可以使用观察者模式。在这种情况下,算法是java.util.Observer,Gui是java.util.Observable。

相关内容

  • 没有找到相关文章

最新更新