Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当按钮函数在另一个类中时如何使用ActionListener_Java_Swing_Actionlistener_Connect - Fatal编程技术网

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

Java 当按钮函数在另一个类中时如何使用ActionListener,java,swing,actionlistener,connect,Java,Swing,Actionlistener,Connect,我有三个不同的类:Main、WindowFrameDimensions和ValidationOfNumber。 Main–调用WindowFrameDimensions。这是主课 WindowFrameDimetnions–调用我正在尝试调用ValidationOfNumber。这是为程序、窗格、框标签和按钮创建框架的类。 ValidationOfNumbers–完成数字验证的所有计算。基本上,该类验证用户键入的数字是否在1..100000范围内 目标: 目标是使用ActionListener将

我有三个不同的类:Main、WindowFrameDimensions和ValidationOfNumber。 Main–调用WindowFrameDimensions。这是主课 WindowFrameDimetnions–调用我正在尝试调用ValidationOfNumber。这是为程序、窗格、框标签和按钮创建框架的类。 ValidationOfNumbers–完成数字验证的所有计算。基本上,该类验证用户键入的数字是否在1..100000范围内

目标: 目标是使用ActionListener将WindowFrameDimensions与ValidationOfNumber连接起来

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

}

您可以尝试进行匿名抽象操作:

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

我们希望这能起作用。尝试将验证文件包导入WindowFrameDimensions

然后是actionlistener的代码

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

在我看来,您正试图实现类似MVC模式的目标。在这种情况下,

您的验证类将被视为模型逻辑和数据 框架类充当视图表示/用户界面 您的主类充当模型和视图之间的Cnotroller中间人 请注意,模型和视图不应该知道彼此的存在。它们通过控制器进行通信

因此,控制器主类应包含图幅类和模型验证类的引用:

//Your controller
public class MainClass{
    private WindowFrameDimentions view;
    private ValidationOfNumbers model;
}
现在,将视图链接到控制器的关键部分是: 由于您的视图不处理逻辑和实现,因此您不直接在此类中为button的action listener编写实现代码,只需添加一个方法来接收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();
    }
}
对于您的验证类,它只是一个简单的验证方法,如下所示:

//The model
public class ValidationOfNumbers{

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

    public boolean validationPassed(String input){
        //your validation code goes here..
    }
}
现在,将所有3个类链接在一起,您有:

//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个类来驱动代码。但在本例中,我使用控制器类来驱动代码


还要注意,实际上应该扩展到JPanel而不是JFrame,然后将扩展类的实例添加到JFrame中。

我得到了以下错误:线程main中的异常java.lang.NullPointerException在BlueBlueBlueMainFiles.WindowFrameDimensions.BuildPanelWindowFrameDimensions.java:67在BlueBlueBlueMainFiles.WindowFrameDimensions.WindowFrameDimensions WindowFrameDimensions.java:45在BlueBlueMainFiles.BlueBlueBlueTheMain.Main BlueBlueTheMain.java:20精选java_工具选项:-Djava.vendor=Sun Microsystems Inc.我的答案来得有点晚,但对于那些有兴趣了解如何链接UI和逻辑的人,可以看看下面的解决方案。