[英]Using ActionListener in another class
因此,我知道已经回答了类似的问题,但是我的问题要更具体一些。 我正在编写一个简单的程序,比较两个输入的单词,然后告诉您它们是否匹配。 这是代码:
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);
}
}
}
所以,我的问题全是关于class Password
,在这一行:
PasswordEngine engine = new PasswordEngine(this);
为什么this
是参数? 为什么该行实际上需要一个参数? 我不明白为什么this
需要在那里。
PS:我是Java和编程的新手。
PasswordEngine
类具有单个构造函数,该构造函数接受类型为Password
的参数:
PasswordEngine(Password parent) {
因此,每当您说出new Password(…)
,…就必须对应于Password
类型的对象(通常可能为null
,但这将在以后导致问题)。 并且由于该参数用于描述将对其应用操作的密码小部件,因此密码小部件将自己(读取this
)作为该参数。 这样, PasswordEngine
知道是哪个Password
对象创建的。
请注意 ,许多应用程序都将嵌套类用于此操作。 嵌套类可以访问其封闭类的成员,因此不需要显式处理parent
类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.