在看《Java 2实用教程》中GUI中的源码时候,出现了一点疑惑,源码如下:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JavaGUI {
public static void main(String[] args) {
WindowActionEvent win = new WindowActionEvent();
PoliceListen police = new PoliceListen();
win.setMyCommandListener(police);
win.setBounds(100, 200, 460, 360);
win.setTitle("处理ActionEven事件");
}
}
class WindowActionEvent extends JFrame {
JTextField inputText;
JTextArea textShow;
JButton button;
MyCommandListener listener;
public WindowActionEvent() {
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init() {
setLayout(new FlowLayout());
inputText = new JTextField(10);
button = new JButton("确定");
textShow = new JTextArea(9, 30);
add(inputText);
add(button);
add(new JScrollPane(textShow));
}
void setMyCommandListener(MyCommandListener listener) {
this.listener = listener;
listener.setJTextField(inputText);
listener.setJTextArea(textShow);
inputText.addActionListener(listener);
button.addActionListener(listener);
}
}
interface MyCommandListener extends ActionListener {
public void setJTextField(JTextField text);
public void setJTextArea(JTextArea area);
}
class PoliceListen implements MyCommandListener {
JTextField textInput;
JTextArea textShow;
public void setJTextField(JTextField text) {
textInput = text;
}
public void setJTextArea(JTextArea area) {
textShow = area;
}
public void actionPerformed(ActionEvent e) {
String str = textInput.getText();
textShow.append(str + "的长度: " + str.length() + "\n");
}
}
这段代码的效果是:
图 1
在文本框输入字符串,下面的文本框就能计算字符串的长度。点击确定按钮,能触发actionPerformed我都能理解,但是,上面源码倒数第四行,也就是下面这行:
String str = textInput.getText();
我就不能理解了,为什么它能直接获得其他类的属性的值?
后来,沿着textInput的前世今生,我发现了这行话:
listener.setJTextField(inputText);
这句话不是别的啊,其实它是将WindowActionEvent类的属性inputText 赋值给 PoliceListen 的属性 textInput。 而这个属性其实是一个对象,也就是对象复制了,说到底,其实是将inputText中存放的引用赋值给textInput。我们画一个图就能很好的理解了:
图 2
所以,inputText对象的改变会引起textInput的改变,同样的,textInput的改变也会引起inputText的改变。
通俗点说,就是上面图1中的文本框内文字的变化,会引起下面的文本框的同步变化。这就是Java中对象复制的美妙之处了。
下面的例子也可以佐证:
public class CopyInstance {
public static void main(String[] args) {
Slave s = new Slave();
Master m = new Master(s);
m.setSlaveString();
System.out.println(s.str);
s.setStr();
System.out.println(m.s.str);
}
}
class Master {
Slave s;
public Master(Slave s) {
this.s = s;
}
public void setSlaveString() {
s.str = "hello";
}
}
class Slave {
String str;
public void setStr() {
str = "world";
}
}
当把Slave s对象赋值给Master对象m的属性s后,这二者就指向了一块内存,一方改变,另一方也跟着改变,跟C语言中的指针是一模一样的,不过,在Java中,更精确地说,叫做引用。
阅读愉快~欢迎批评指正!