简体   繁体   English

如何在Java中编写ActionListener

[英]How to write actionlistener in java

Below is my codes: 下面是我的代码:

JLabel label1 = new JLabel("testcontent");
label1.setBounds(131, 57, 205, 74);

frame.getContentPane().add(label1);

JButton btn1 = new JButton("run");
btn1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

    }
});

btn1.setBounds(169, 206, 117, 25);
frame.getContentPane().add(btn1);

When I try to refer the label1 in the actionPerformed, eclipse cannot find the label1. 当我尝试在actionPerformed中引用label1时,eclipse无法找到label1。 Any one could tell me what's wrong? 谁能告诉我怎么了?

label1 is not available in the scope of the ActionListener . label1ActionListener的范围内不可用。 Either declare it as final or make it a class instance variable 将其声明为final或使其成为类实例变量

final JLabel label1 = new JLabel("testcontent");

You can get around using final by doing what is described in this answer. 您可以通过执行答案中所述的内容来使用final

Basically, you pass in the label through an init method that you call immediately after creating an anonymous object. 基本上,您通过创建匿名对象后立即调用的init方法传递标签。 In your case, it would look something like this: 就您而言,它看起来像这样:

btn1.addActionListener(new ActionListener() {
    private JLabel myLabel;
    private ActionListener init(JLabel var){
        myLabel = var;
        return this;
    }
    public void actionPerformed(ActionEvent e) {

    }
}.init(myVariable));

The reference myLabel is then accessible within btn1 's actionPerformed method. 然后,可以在btn1actionPerformed方法中访问引用myLabel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM