简体   繁体   中英

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. so I have to accept the cell value aka String s from one class and transfer to another class and use it there. But I don't know how to pass it. I'm guessing I have to use Getter Setter method but idk how.

If you are interested in learned basic Getters and Setters, this example should help you:

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. Class1 is the class that will be getting/setting the private String in 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 modifiers

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 ). It should be used in setter methods to differentiate between the class variable and the parameter because they have the same name.

I hope this helps with passing values between classes!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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