简体   繁体   English

在 java netbeans 中调用方法

[英]Call a method in java netbeans

I want to write clear button method in one class in another package.我想在另一个包的一个类中编写清除按钮方法。 And i want to call that method in clear button as button click event.我想在清除按钮中调用该方法作为按钮单击事件。

Eg-例如-

Package A class a <---- I want to write method in here. Package A class a <---- 我想在这里写方法。

Package B class b <---- in here i have that clear button i want to call that method here.包 B 类 b <---- 在这里,我有一个清除按钮,我想在这里调用该方法。

I'm facing some error in text fields!!!.我在文本字段中遇到了一些错误!!!。

public boolean Clear(){
    boolean clearDate =false;
    Connection dbConn = null;

    StaffId_Text.setText("");
    First_Name_Text.setText("");
    Middle_Name_Text.setText("");
    Last_Name_Text.setText("");
    Civil_Status_Text.setText("");
    NIC_Text.setText("");
    Email_Text.setText("");
    Address_Text.setText("");
    Contact_Number_Text.setText("");

    return clearDate;
}

In order to use a variable inside a method this variable has to be "known" there.为了在方法中使用变量,该变量必须在那里“已知”。 This can be done either be declare a variable like private String text or by passing the variable to method as an argument like b.Clear(textField) .这可以通过声明一个像private String text这样的变量来完成,也可以通过将变量作为参数传递给方法,如b.Clear(textField) That way the method Clear knows the variable textField and can work with it.这样,方法Clear知道变量textField并且可以使用它。

This is an example how this can be done:这是如何做到这一点的示例:

public boolean clear(JTextField... textfields) { // method names should begin
    boolean clearDate = false;                   // with a lower case letter
    Connection dbConn = null;

    for (JTextField textField : textfields) {
        textField.setText("");
    }

    return clearDate;
}

Here I declare a method called clear which will take an amount of variables of type JTextField .在这里,我声明了一个名为clear的方法,它将接受大量JTextField类型的变量。 Inside that method I iterate over every passed JTextField and call the method setText("") on it.在该方法中,我遍历每个传递的 JTextField 并在其上调用方法setText("")

Now you can call your method like this:现在你可以像这样调用你的方法:

public void clearEvent() {
    b.clear(staffIdText, firstNameText, middleNameText, [and so on...]);
}

You can pass as many JTextFields to this method as you like.您可以根据需要将任意数量的 JTextField 传递给此方法。

You can also use a list like I mentioned in the comment, but I guess this variant here is much more convenient.您也可以使用我在评论中提到的列表,但我想这里的这个变体要方便得多。

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

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