![](/img/trans.png)
[英]How we are able to access private instance variable with getter and setter?
[英]How to apply Getter/Setter method for private variable in GUI?
該程序的目的是從另一個類訪問私有變量jtextfield。 我創建了這個簡單的程序,它從JTextField獲取用戶輸入。 我在一個類中有getter和setter方法,在另一個類中有按鈕和字段。 因此,我想在用戶在文本字段中鍵入內容時打印一些內容。 但是當單擊該按鈕時,程序不會打印並給出錯誤:
錯誤:javax.swing.JTextField [,140,62,124x20,layout = javax.swing.plaf.basic.BasicTextUI
我是否正確初始化了getter和setter方法?
例1:
import javax.swing.*;
class Example1 {
private JTextField Name;
public Example1(){
Name = null;
}
public Example1(JTextField n){
Name = n;
}
public void setName(JTextField Name) {
this.Name = Name;
}
public JTextField getName() {
return Name;
}
}
例2:
import javax.swing.*;
import java.awt.event.*;
public class Example2
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
private JTextField Name = new JTextField();
private JButton Button = new JButton("Print");
public Example2(){
panel.setLayout(null);
Name.setBounds(140, 62, 124, 20);
Button.setBounds(320, 62, 133, 20);
panel.add(Name);
panel.add(Button);
frame.add(panel);
frame.setSize(470,310);
frame.setVisible(true);
Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
add(Name);
}
});
}
public static void add(JTextField Name){
Example1 x = new Example1();
x.setName(Name);
JTextField a = x.getName();
System.out.println(a);
}
public static void main(String [] args){
Example2 print = new Example2();
}
}
您不希望打印要通過文本字段訪問字符串保持的元素本身。 這不是錯誤。 它只是為JTextField調用toString()方法。
使用textfield.getText()
來訪問Textfield的值。 在Example2中,這將是:
public static void add(JTextField Name){
Example1 x = new Example1();
x.setName(Name);
JTextField a = x.getName();
System.out.println(a.getText());
}
希望這可以幫助。
你所看到的不是錯誤。 這是打印沒有定義toString()
方法的對象的結果。
JTextField a = x.getName();
System.out.println(a);
將對象傳遞給System.out.println()
,將調用toString()
對象。 由於JTextField沒有toString()
,因此調用標准的Object.toString()
方法。
更好的方法是:
System.out.println(a.getText());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.