I was writing a program, and then I saw this on some website that is using the this keyword in this code, and I was wondering what it's purpose, it can process a Jbutton, or JTextField, it can show message using the this keyword, what happened to getSource()?
Here's the code
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
public class TextPassWordEvent extends JFrame {
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
private JPasswordField passwordField;
private JButton button;
public TextPassWordEvent(){
super("Title");
setLayout(new FlowLayout());
textField1 = new JTextField(10);
add(textField1);
textField2 = new JTextField("Enter your Text Here");
add(textField2);
textField3 = new JTextField("Uneditable Text field");
textField3.setEditable(false);
add(textField3);
passwordField = new JPasswordField("Password");
add(passwordField);
button = new JButton("Submit");
add(button);
TextHandler handler = new TextHandler();
textField1.addActionListener(handler);
textField2.addActionListener(handler);
textField3.addActionListener(handler);
passwordField.addActionListener(handler);
button.addActionListener(handler);
}
private class TextHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(TextPassWordEvent.this, String.format("Message: %s",event.getActionCommand()));
}
}
}
You are looking at an inner class. In this scenario, there even several versions of this.
A plain this would be the instance of the inner class (i.e. TextHandler). If you need to refer to the instance of the containing class, you have to qualify it with the class name: TextPassWordEvent.this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With