簡體   English   中英

當按鈕函數在另一個類中時如何使用ActionListener

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

我有三個不同的類:Main,WindowFrameDimetnions和ValidationOfNumbers。 Main –調用WindowFrameDimetnions。 它是WindowFrameDimetnions的主要類-調用(我正在嘗試調用)ValidationOfNumbers。 這是為程序創建框架,窗格,框標簽和按鈕的類。 ValidationOfNumbers –是進行所有數字驗證的計算的程序。 基本上,此類驗證使用類型輸入的數字在1..100,000范圍內。

目標:目標是通過使用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);

    }
}

現在,這是另一個代碼:

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);
             }
    }

}

您可以嘗試制作一個匿名的AbstractAction:

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

希望這應該工作..嘗試將包TheValidationFiles導入WindowFrameDimentions

然后為動作偵聽器編碼

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

在我看來,您正在嘗試實現類似MVC模式的功能。 在這種情況下,

  • 您的Validation類將被視為Model(邏輯和數據)
  • 您的Frame類充當View(演示/用戶界面)
  • 您的Main類充當Cnotroller(模型和視圖的中間人)

請注意,模型和視圖不應該知道彼此的存在。 它們通過控制器進行通信。

因此,您的Controller(主類)應持有View(框架類)和模型(驗證類)的引用:

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

現在,將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();
    }
}

對於您的Validation類,這只是一種簡單的驗證方法,如下所示:

//The model
public class ValidationOfNumbers{

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

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

現在,將所有三個類鏈接在一起,您將擁有:

//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
            }
        });
    }
}

這是鏈接所有3個類的總體思路。 通常,實現MVC時,我將擁有4個類而不是3個類,還有1個類來驅動代碼。 但是在此示例中,我使用Controller類來驅動代碼。

還要注意,您實際上應該擴展到JPanel而不是JFrame,然后將擴展類的實例添加到JFrame。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM