ActionListener上的Symbol not Found错误

时间:2015-12-15 08:41:45

标签: java swing awt actionlistener

import javax.swing .*;    
import java.awt.event.ActionListener;    
import java.awt.event.ActionEvent;   
import java.awt.*;    
import javax.swing.JOptionPane;   
import java.io.FileWriter;    
class Myclass extends JFrame  
{
    Myclass()
    {
    setLayout(null);
    setLayout(new FlowLayout());
    //setBounds(50,50,700,700);
    JLabel lfname=new JLabel("Name ");
    JLabel llname=new JLabel("Lastname ");
    JLabel lmidname=new JLabel("Middlename ");
    JTextField tname=new JTextField(15);
    JTextField tmidname=new JTextField(15);
    JTextField tlastname=new JTextField(15);
    add(lfname);add(tname);
    add(lmidname);add(tmidname);
    add(llname);add(tlastname);
    JButton addrec=new JButton("Add Record");
    JButton delrec=new JButton("Delete Record");
    GridBagConstraints g=new GridBagConstraints();

    JPanel p=new JPanel(new GridLayout(1,2,20,20));

    add(p);

    p.add(addrec);
    p.add(delrec);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    /*tname.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent oe)
            {
                System.out.println("Text="+tname.getText());
            }


});*/
    //tname.addActionListener(obj);
JButton save=new JButton("Save");
MyListener obj=new MyListener();
add(save);
save.addActionListener(obj);

    setVisible(true);



}


public static void main(String args[])
{
    new Myclass();


 }

class MyListener implements ActionListener
 {

    public void actionPerformed(ActionEvent oe)
    {

            //if(ae.getSource().equals(calRect))
            if(oe.getSource().equals(save))
                {
                FileWriter fw=null;
                try{
                        fw=new FileWriter("c:\\users\\dell\\desktop\\File.txt");
                    }catch(Exception e){}

                }
    }

}

我试图通过在Mylistener类上实现ActionListener来添加名为Mylistener的自定义侦听器
我不知道这段代码的错误,但在actionPerformed()中,if条件的开始是错误的位置。谁能纠正我的代码?

Error is Layout.java:69: error: cannot find symbol
                                if(oe.getSource().equals(save))

                                                     ^
symbol:   variable save
location: class MyListener
1 error

1 个答案:

答案 0 :(得分:1)

您的保存按钮未在侦听器类中定义。您必须将它作为参数添加到构造函数中:

class MyListener implements ActionListener {

  private JButton save;
  public MyListener(JButton save){
    this.save = save;
  }
  public void actionPerformed(ActionEvent oe) {

    // if(ae.getSource().equals(calRect))
    if (oe.getSource().equals(save)) {
      FileWriter fw = null;
      try {
        fw = new FileWriter("c:\\users\\dell\\desktop\\File.txt");
      } catch (Exception e) {}

    }
  }


//tname.addActionListener(obj);
JButton save=new JButton("Save");
MyListener obj=new MyListener();
add(save);
save.addActionListener(obj);