简体   繁体   English

将变量从 JFrame Class 的私有方法传递给另一个 Jframe ZA2F2ED4F8EBC2CBB4C21A29DC40AB6D

[英]Passing a variable from private method of JFrame Class to another Jframe class

       
        
        JTable source = (JTable) evt.getSource();
                int row = source.getSelectedRow();
                int col = source.getSelectedColumn();
                String s = source.getModel().getValueAt(row, col) + "";
             
             
             UpdateOrDelete ob= new UpdateOrDelete();
             BookListInfo.this.setVisible(false);
                ob.setVisible(true);
                ob.setLocationRelativeTo(null);
             
    }

So I am creating a Library Management System and am kind of new to JFrames.所以我正在创建一个图书馆管理系统,并且对 JFrames 有点陌生。 so I have to accept the cell value aka String s from one class and transfer to another class and use it there.所以我必须从一个 class 接受单元格值 aka String 并转移到另一个 class 并在那里使用它。 But I don't know how to pass it.但我不知道如何通过它。 I'm guessing I have to use Getter Setter method but idk how.我猜我必须使用 Getter Setter 方法,但不知道如何使用。

If you are interested in learned basic Getters and Setters, this example should help you:如果您对学习过的基本 Getter 和 Setter 感兴趣,这个示例应该可以帮助您:

Notice that the class being referenced ( Class2 ) is instantiated in the scope that it is needed in. This probably won't be in your "main" method but I have used it as an example.请注意,引用的 class ( Class2 )在需要它的 scope 中实例化。这可能不在您的“主要”方法中,但我已将其用作示例。 Class1 is the class that will be getting/setting the private String in Class2 . Class1是 class ,它将在Class2中获取/设置私有字符串。

public class Class1 {
    public static void main(String[] args) {
        //Instantiating Class2
        Class2 c2 = new Class2();
        //Using the setter method to set the value of privateString
        c2.setPrivateString("This String has been modified");
        //Using the getter method to get the value of privateString and printing it
        System.out.println(c2.getPrivateString());
    }
}

In Class2 , pay attention to the access modifiersClass2中,注意访问修饰符

public class Class2 {
    //Notice that the access modifier is private
    private String privateString = "This String is private";

    //Setter method for privateString
    public void setPrivateString(String privateString) {
        this.privateString = privateString;
    }

    //Getter method for privateString
    public String getPrivateString() {
        return privateString;
    }
}

this is a keyword for the object that the code is in (in this case that is Class2 ). this是代码所在的 object 的关键字(在本例中为Class2 )。 It should be used in setter methods to differentiate between the class variable and the parameter because they have the same name.应该在设置方法中使用它来区分 class 变量和参数,因为它们具有相同的名称。

I hope this helps with passing values between classes!我希望这有助于在类之间传递值!

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

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