简体   繁体   English

当按钮函数在另一个类中时如何使用ActionListener

[英]How to use ActionListener when the button function is in another class

I have three different classes: Main, WindowFrameDimetnions, and ValidationOfNumbers. 我有三个不同的类:Main,WindowFrameDimetnions和ValidationOfNumbers。 Main – Calls WindowFrameDimetnions. Main –调用WindowFrameDimetnions。 It is the main class WindowFrameDimetnions – Calls (well I am trying to call ) ValidationOfNumbers. 它是WindowFrameDimetnions的主要类-调用(我正在尝试调用)ValidationOfNumbers。 This is the class that creates the frame for the program, the pane, the label for the box, and the button. 这是为程序创建框架,窗格,框标签和按钮的类。 ValidationOfNumbers – is the one that does all the calculations for number validations. ValidationOfNumbers –是进行所有数字验证的计算的程序。 Basically this class validates that the numbers typed by the use are within the range of 1..100,000. 基本上,此类验证使用类型输入的数字在1..100,000范围内。

Goal: The goal is to connect WindowFrameDimetnions with ValidationOfNumbers by using an ActionListener. 目标:目标是通过使用ActionListener将WindowFrameDimetnions与ValidationOfNumbers连接。

package BlueBlueMainFiles;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class WindowFrameDimentions extends JFrame{

    final static int WINDOW_WITH    = 950;//Window with in pixel
    final static int WINDOW_HEIGH   = 650;//Window height in pixel
    static JPanel       panel;//use to reference the panel
    static JLabel       messageLabel;//use to reference the label 
    static JTextField   textField;//use to reference the text field
    static JButton      calcButton;//use to reference the button 

    public WindowFrameDimentions() {
        // TODO Auto-generated constructor stub
    }

    public static void windowFrameDimentions(){
        //create a new window
        JFrame window = new JFrame();

        //add a name to the window
        window.setTitle("BLUE BLUE");

        //set the size of the window
        window.setSize(WINDOW_WITH, WINDOW_HEIGH);

        //specify what happens when the close button is pressed 
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //BUILD THE PANEL AND ADD IT TO THE FRAME
        buildPanel();

        //ADD THE PANEL TO THE FRAMES CONTENT PANE
        window.add(panel);

        //Display the window
        window.setVisible(true);
    }

    public static void buildPanel(){
        //create a label to display instructions
        messageLabel = new JLabel("Enter a Number from 1..100,000");

        //create a text field of 10 characters wide
        textField = new JTextField(10);

        //create panel
        calcButton = new JButton("Calculate");


        //Add an action listening to the button. Currently, I can't make it work


        //Create the a JPanel object and let the panel field reference it
        panel = new JPanel();

        panel.add(messageLabel);
        panel.add(textField);
        panel.add(calcButton);

    }
}

Now this is the other code: 现在,这是另一个代码:

package TheValidationFiles;


public class  ValidationOfNumbers {

    static int MAX_NUMBER_TO_VAL = 10000000;

    public static void GetValidationOfNumbers(boolean isTrue, String s) {

             String[] numberArray = new String [MAX_NUMBER_TO_VAL];
             boolean numberMatching = false;

             for (int i = 0; i < MAX_NUMBER_TO_VAL; i++){
                     numberArray[i] = Integer.toString(i);

                     if (numberArray[i].equals(s)){
                         System.out.println("The number you typed " + s + " Matches with the array value of: " + numberArray[i]);
                         System.exit(0);
                         break;
                     }
                     else{
                         numberMatching = true;
                     }
             }
             if(numberMatching){
                 ValidationOfFiles.ValidationOfFiles(s);
             }
    }

}

You can try to make an anonymous AbstractAction: 您可以尝试制作一个匿名的AbstractAction:

panel.add(new JButton(new AbstractAction("name of button") {
    public void actionPerformed(ActionEvent e) {
        //do stuff here
    }
}));

well hope this should work..try importing package TheValidationFiles into WindowFrameDimentions 希望这应该工作..尝试将包TheValidationFiles导入WindowFrameDimentions

then code for actionlistener 然后为动作侦听器编码

calcButton.addActionListener(new ActionListener(){
  public void actionPerformed(ActionEvent ae){
     ValidationOfNumbers von=new ValidationOfNumbers();
     von.GetValidationOfNumbers(boolean value,string);
  }});

It seems to me you are trying to achieve something like a MVC pattern. 在我看来,您正在尝试实现类似MVC模式的功能。 In this case, 在这种情况下,

  • Your Validation class will be treated as the Model (logic and data) 您的Validation类将被视为Model(逻辑和数据)
  • Your Frame class acts as the View (presentation / user interface) 您的Frame类充当View(演示/用户界面)
  • Your Main class acts as the Cnotroller (middleman betweem Model and View) 您的Main类充当Cnotroller(模型和视图的中间人)

Note that Model and View should not know the existence of one another. 请注意,模型和视图不应该知道彼此的存在。 They communicate via the Controller. 它们通过控制器进行通信。

Hence your Controller (Main class) should hold a reference of View (Frame class) and Model (Validation class): 因此,您的Controller(主类)应持有View(框架类)和模型(验证类)的引用:

//Your controller
public class MainClass{
    private WindowFrameDimentions view;
    private ValidationOfNumbers model;
}

Now the crucial part to link View to your Controller: Because your view does not handle the logic and implementation, hence you don't code the implementation for button's action listener in this class directly, instead, just add a method to receive an ActionListener: 现在,将View链接到Controller的关键部分:因为您的视图无法处理逻辑和实现,因此您不必直接在此类中为按钮的动作监听器编写实现代码,而是只需添加一个方法即可接收ActionListener:

//The view
public class WindowFrameDimentions{
    private JButton calcButton;
    private JTextField textField;    //please use a better name for this

    public WindowFrameDimentions(){
        //Initialize all other required attributes here..
        calcButton = new JButton("Calculate");
    }

    //The controller will create a listener and add to calcButton
    public void addCalcButtonListener(ActionListener listener){
        calcButton.addActionListener(listener)
    }

    //You need a getter for all the input fields such as your JTextFields
    public String getInput(){
        textField.getText();
    }
}

For your Validation class, it will be just a simple method to validate like this: 对于您的Validation类,这只是一种简单的验证方法,如下所示:

//The model
public class ValidationOfNumbers{

    public ValidationOfNumbers(){
        //Initialize all other required attributes here..
    }

    public boolean validationPassed(String input){
        //your validation code goes here..
    }
}

Now, linking all 3 classes together, you have: 现在,将所有三个类链接在一起,您将拥有:

//The controller
public class MainClass{
    private WindowFrameDimentions view;
    private ValidationOfNumbers model;

    public static void main(String[] args){
        view = new WindowFrameDimentions();
        model = new ValidationOfNumbers();
        view.addCalcButtonListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                //Now, we can use the Validation class here
                if(model.validationPassed(view.getInput())){  //Linking Model to View
                    //If validation passes, do this
                }
                //Any other actions for calcButton will be coded here
            }
        });
    }
}

This is the overall idea of linking all 3 classes. 这是链接所有3个类的总体思路。 Normally, I would have 4 classes instead of 3 when implementing MVC, 1 more class to drive the codes. 通常,实现MVC时,我将拥有4个类而不是3个类,还有1个类来驱动代码。 But in this example, I use Controller class to drive the codes. 但是在此示例中,我使用Controller类来驱动代码。

Also note that, you should actually be extending to a JPanel instead of a JFrame, then add the instance of the extended class to the JFrame. 还要注意,您实际上应该扩展到JPanel而不是JFrame,然后将扩展类的实例添加到JFrame。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM