所以,我知道已经回答了类似的问题,但我的问题更具体一些。我正在编写一个简单的程序,它比较两个输入的单词,然后告诉你它们是否匹配。这是代码:
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
public class Password {
JPanel windowContent, p1, p2, p3; //p1 is in the west, p2 in center and p3 in south
JButton check, clear;
JTextField pass1, pass2;
JLabel word1, word2, result;
JFrame frame;
Password() {
windowContent = new JPanel();
BorderLayout bl = new BorderLayout();
windowContent.setLayout(bl);
p1 = new JPanel();
GridLayout gl = new GridLayout(2, 1);
p1.setLayout(gl);
word1 = new JLabel("1st word: ");
word2 = new JLabel ("2nd word: ");
p1.add(word1);
p1.add(word2);
windowContent.add("West", p1);
p2 = new JPanel();
p2.setLayout(gl);
pass1 = new JTextField (20);
pass2 = new JTextField (20);
p2.add(pass1);
p2.add(pass2);
windowContent.add("Center", p2);
p3 = new JPanel();
FlowLayout fl = new FlowLayout();
p3.setLayout(fl);
check = new JButton("Check");
clear = new JButton("Clear");
result = new JLabel("");
p3.add(check);
p3.add(result);
p3.add(clear);
windowContent.add("South", p3);
frame = new JFrame("Password");
frame.add(windowContent);
frame.pack();
frame.setVisible(true);
PasswordEngine engine = new PasswordEngine(this); // <--- THIS LINE HERE!
check.addActionListener(engine);
clear.addActionListener(engine);
}
public static void main(String [] args) {
Password pass = new Password();
}
}
在另一个类中,程序逻辑:
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PasswordEngine implements ActionListener {
Password parent;
String textField1, textField2;
PasswordEngine(Password parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
String displayFieldText1 = parent.pass1.getText();
String displayFieldText2 = parent.pass2.getText();
Object src = e.getSource();
if (src == parent.clear) {
parent.pass1.setText("");
parent.pass2.setText("");
parent.result.setText("");
parent.pass1.setBackground(Color.white);
parent.pass2.setBackground(Color.white);
} else if (displayFieldText1.equals(displayFieldText2)) {
parent.result.setText("MATCH");
parent.pass1.setBackground(Color.GREEN);
parent.pass2.setBackground(Color.GREEN);
} else {
parent.result.setText("NOT MATCH");
parent.pass1.setBackground(Color.white);
parent.pass2.setBackground(Color.white);
}
}
}
所以,我的问题都是关于 classPassword
的,在这一行:
PasswordEngine engine = new PasswordEngine(this);
为什么是this
参数?为什么那条线实际上需要一个参数?我不明白为什么this
它需要在那里。
PS:我是 Java 和编程新手。