b1.addActionListener(this);在这条语句中,'this‘关键字的用法是什么,通过'this’关键字传递的引用是什么?如果可能的话,请告诉我例子。
发布于 2013-07-13 14:18:31
" this“表示此对象,如果您编写此语句,则表示您的类实现了ActionListener
例如:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class test extends JFrame implements ActionListener {
JButton someButton;
test() {
// create the button
someButton = new JButton();
// add it to the frame
this.add(someButton);
// adding this class as a listener to the button, if button is pressed
// actionPerformed function of this class will be called and an event
// will be sent to it
someButton.addActionListener(this);
}
public static void main(String args[]) {
test c = new test();
c.setDefaultCloseOperation(EXIT_ON_CLOSE);
c.setSize(300, 300);
c.setVisible(true);
c.setResizable(false);
c.setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == someButton)
{
JOptionPane.showMessageDialog(null, "you pressed somebutton");
}
}
};发布于 2013-07-13 14:26:39
this引用object的当前实例。
假设您的类A实现了ActionListener。然后从你的类中,如果你添加了listener,那么你可以使用这个,至于继承规则,你的类也是一个listener。
class A implements ActionListener{
Button b;
A(){
b1 = new Button();
b1.addActionListener(this);
}
}在这里使用它是因为currentobject也是一个操作侦听器
https://stackoverflow.com/questions/17627519
复制相似问题