How to pass user input from GUI to main class

I'm just starting to work with Java Swing again, and I have the same problem as last time. I want to write a program that reads user input, executes an algorithm, and displays the result. The program should work with two different user interfaces (console and GUI with Java Swing).

Currently, I have a class package with an algorithm (I can just pass the user input and get the result), a class that contains the main class, a class for the console interface and a class for the graphical interface (which extends from JFrame). Some code:


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 {
}

, , (, , ) .

GUI GUI?
ActionListener MainClass ( )? , ?
?: D

+3
3

: ( , ).

: Model-View-Controller (MVC), , , - . ( ) : http://martinfowler.com/eaaDev/uiArchs.html

:

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 .

+2

, , . shoul donly , GUI .

, , , :

  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");
0

You can use the observer pattern. In this case, the algorithm is java.util.Observer, and Gui is java.util.Observable.

0
source

All Articles