如何在Java中处理事件?

如何在Java中处理事件?,java,events,event-handling,Java,Events,Event Handling,我刚刚用java制作了第一个基于事件的GUI, 但我不明白我错在哪里。 当没有应用事件处理时,代码工作正常 这是密码 package javaapplication1; import javax.swing.*; import java.awt.event.*; class Elem implements ActionListener{ void perform(){ JFrame frame = new JFrame(); JButton but

我刚刚用java制作了第一个基于事件的GUI, 但我不明白我错在哪里。 当没有应用事件处理时,代码工作正常

这是密码

package javaapplication1;

import javax.swing.*;
import java.awt.event.*;

 class Elem implements ActionListener{

    void perform(){
        JFrame frame = new JFrame();
        JButton button;
        button = new JButton("Button");
        frame.getContentPane().add(button) ;
        frame.setSize(300,300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        button.addActionListener(this);
     }

    public void actionPerformed(ActionEvent ev){
        button.setText("Clicked");
    }
}

 public class JavaApplication1 {

  public static void main(String[] args) {
   Elem obj = new Elem();
   obj.perform();
  }  
}

当您使用
按钮
方法中的
actionPerformed
对象时。因此,全局声明
按钮

class Elem implements ActionListener{
     JButton button;// Declare JButton here.
    void perform(){
        JFrame frame = new JFrame();

        button = new JButton("Button");
        frame.getContentPane().add(button) ;
        frame.setSize(300,300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        button.addActionListener(this);
     }

    public void actionPerformed(ActionEvent ev){
        button.setText("Clicked");
    }
}

 public class JavaApplication1 {

  public static void main(String[] args) {
   Elem obj = new Elem();
   obj.perform();
  }  
}

变量范围存在问题。移动
JButton按钮
perform()
方法之外的定义,以便
actionPerformed()
可以访问它

JButton button;

void perform(){
    JFrame frame = new JFrame();
    button = new JButton("Button");
    frame.getContentPane().add(button) ;
    frame.setSize(300,300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    button.addActionListener(this);
 }
在方法内部定义对象时(例如,
perform()
),其范围仅限于该方法(在花括号内)。这意味着类中的其他方法无法访问该变量

通过将对象定义移到方法之外,它现在具有类级别的作用域。这意味着该类中的任何方法都可以访问该变量。您仍然在
perform()
中定义它的值,但现在可以通过其他方法访问它,包括
actionPerformed()


请参阅以获取更多解释。

那么,应该发生什么以及现在发生了什么?错误是什么?这段代码可以编译吗?是的,它也可以编译和运行,但只要我单击按钮,就会抛出大约10个错误:\n这意味着可见性。声明在block.hmmm.之外不可见。。明白了。谢谢