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

所以我正在創建一個圖書館管理系統,並且對 JFrames 有點陌生。 所以我必須從一個 class 接受單元格值 aka String 並轉移到另一個 class 並在那里使用它。 但我不知道如何通過它。 我猜我必須使用 Getter Setter 方法,但不知道如何使用。

如果您對學習過的基本 Getter 和 Setter 感興趣,這個示例應該可以幫助您:

請注意,引用的 class ( Class2 )在需要它的 scope 中實例化。這可能不在您的“主要”方法中,但我已將其用作示例。 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());
    }
}

Class2中,注意訪問修飾符

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是代碼所在的 object 的關鍵字(在本例中為Class2 )。 應該在設置方法中使用它來區分 class 變量和參數,因為它們具有相同的名稱。

我希望這有助於在類之間傳遞值!

暫無
暫無

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

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