[英]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.